Search code examples
c#arraysmultidimensional-arrayindexoutofboundsexception

cannot get length of 2d array having array names in it


I cant get length of 2d array having other array names inside it. Like..

int[] a = { 1, 2, 3 };
int[] b = { 23, 4, 6 };
int[][] ab = { a, b };
int r = ab.GetLength(1);

Solution

  • GetLength(1) is intended for 2D arrays, you have a jagged array (array of arrays) and all your arrays only have a single dimension. As such, you cannot have 1 as an argument to GetLength

    I would, for example:

    int r = ab[1].Length; // the length of the 23,4,6 array
    

    Also:

    ab.Length //it is 2, there are two 1D arrays in ab
    

    We call it jagged because it doesn't have to have the same length array in each slot:

    ab[0] = new int[]{1,2,3,4,5};
    ab[1] = new int[]{1,2,3,4};