1

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?

2
  • It's a jagged array, not a square array (which you declare with char[,] maz). Each sub array is going to have a different length. that you check with maz[index].Length. Commented Feb 23, 2017 at 14:17
  • Don't use GetLenght(), rather Length of individual item of first array. Commented Feb 23, 2017 at 14:17

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Array.GetLength(int dimension) is only for multi-dimensional arrays. Your array 'm' is not multi-dimensional, but jagged.

That means it's an array with element type char[].

So you only have one dimension (with length 10) and GetLength(1) throws the error.

You can get m[i].Length for i from 0 to 9. But only if you initialized the elements:

m[0] = new char[10];
int l = m[0].Length; // 10

1 Comment

Technically speaking, you can use GetLength for any kind of array. It will just throw an exception if you try to query a dimension that doesn't exist, and for every non-multidimensional array, the only dimension that exists is 0. (There's also the fact that there's literally no reason to use GetLength on a non-multidimensional array since Length is both faster and more convenient.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.