Search code examples
c#jagged-arrays

C# Jagged array: outside the bounds of the array issue


I have a jagged array declared as:

char[][] m = new char[10][];

Later it is populated.

System.Text.StringBuilder s = new System.Text.StringBuilder(c);
for (int x = 0; x < 10; x++)
    s.Append('=');

    for (int x = 0; x < 10; x++) m[x] = s.ToString().ToCharArray();

If I perform the below operations, I get an error on the second dimension:

Console.WriteLine(String.Format("width={0}", m.GetLength(0)));
Console.WriteLine(String.Format("height={0}", m.GetLength(1))); <---- ERROR HERE

Any ideas?


Solution

  • You are confusing square arrays and jagged arrays. A jagged array is also known as an array of arrays, and it looks like this:

    char[][] a = new char[10][];
    

    Each element in a jagged array is an array in its own right, and it can have a completely different length from any of the others:

    a[0] = new char[1];
    a[1] = new char[100];
    a[2] = new char[5];
    ...
    a[9] = new char[999999];
    

    As you can see, GetLength(1) makes no sense on a jagged array. What would it even return? To get the lengths of the second level of arrays, you would have to iterate through them and call their various Length properties:

    for (int i = 0; i < a.Length; i++)
    {
        int length = a[i].Length;
    }
    

    For your purposes, you probably want to use a square array (also known as a 2D array) instead:

    char[,] a = new char[10,10];
    

    Unlike a jagged array, the second dimension of a square array is guaranteed to be the same length. That means GetLength(1) can return a value with confidence.