1

The below listed code is to help me find the row and column size for a 2-dimensional array in C#, but I end up with a IndexOutOfRangeException when accessing the column-length(GetLength(1)). I did look-up similar s.o q-a's, but could not figure out the column size.

  List<List<int>> intLists = new List<List<int>>();
  for (int i = 0; i < 2; i++)
  {
    List<int> tempList = new List<int>();
    for (int j = 0; j < 5; j++)
      tempList.Add(j + 5+i);
    intLists.Add(tempList);
  }

  int[][] intArray = intLists.Select(Enumerable.ToArray).ToArray();

  Console.WriteLine("Dimension 0 Length = " + intArray[0].Length);
  Console.WriteLine("Dimension 1 Length = " + intArray[1].Length);
  Console.WriteLine("Dimension 0 Length = " + intArray.GetLength(0));
  //Console.WriteLine("Dimension 1 Length = " + intArray.GetLength(1));
Community
  • 1
  • 1
rahul
  • 407
  • 1
  • 6
  • 20

1 Answers1

5

intArray is an array of arrays, it is not a 2D array. Array.GetLength works only with multidimentional array (int[,]) because intArray[0].Length may be different from intArray[1].Length

Check this answer for more details:

What are the differences between a multidimensional array and an array of arrays in C#?

Community
  • 1
  • 1
Ahmed KRAIEM
  • 10,267
  • 4
  • 30
  • 33