There a section in my code where I need to invert a matrix. That can only reasonably be done on a square matrix, in this case a 3×3 square matrix. The tool I’m using to invert the matrix kept saying that my array wasn’t a proper square.
So I did a little test:
double[,] x = new double[3, 3];
MessageBox.Show(x.GetLength(0).ToString());
MessageBox.Show(x.GetLength(1).ToString());
MessageBox.Show(x.GetLength(2).ToString());
First one comes up as “3”. Second one comes up as “3”. Third one comes up as an IndexOutOfRangeException. Am I just overlooking something extremely obvious or… is this a little weird?
(Note: This is code from C# using .Net 2.0)
You only have an array with two dimensions. Why would you expect asking for the size of the third dimensions to give you a valid result?
The
Array.GetLength()method return the number of elements in the specified dimension of the Array. In your case:you’re asking a 2-dimensional array what the size of it’s third dimension is. The result is an
IndexOutOfRangeException. This is the expected behavior.In your code example, it looks like you may be confusing the size of each stated dimension, with the number of dimensions. Here are some examples of rectangular arrays of different dimensions:
See the pattern? The number of dimensions is determined by how many numbers you specify in the array declaration. The sizes of each dimension is determined by the values of each number in the declaration.