Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the width and height of a multi-dimensional array?

People also ask

How do you determine the size of a multidimensional array?

We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.

How do I get the size of an array in C#?

Length Property is used to get the total number of elements in all the dimensions of the Array. Basically, the length of an array is the total number of the elements which is contained by all the dimensions of that array.

What is multi dimension array?

A multidimensional array in MATLAB® is an array with more than two dimensions. In a matrix, the two dimensions are represented by rows and columns. Each element is defined by two subscripts, the row index and the column index.

What are the dimensions of an array?

The dimensionality of an array is how many axes it has. You index into it with one subscript, e.g. array[n] . You index into it with two subscripts, e.g. array[x,y] .


You use Array.GetLength with the index of the dimension you wish to retrieve.


Use GetLength(), rather than Length.

int rowsOrHeight = ary.GetLength(0);
int colsOrWidth = ary.GetLength(1);

// Two-dimensional GetLength example.
int[,] two = new int[5, 10];
Console.WriteLine(two.GetLength(0)); // Writes 5
Console.WriteLine(two.GetLength(1)); // Writes 10

Some of the other posts are confused about which dimension is which. Here's an NUNIT test that shows how 2D arrays work in C#

[Test]
public void ArraysAreRowMajor()
{
    var myArray = new int[2,3]
        {
            {1, 2, 3},
            {4, 5, 6}
        };

    int rows = myArray.GetLength(0);
    int columns = myArray.GetLength(1);
    Assert.AreEqual(2,rows);
    Assert.AreEqual(3,columns);
    Assert.AreEqual(1,myArray[0,0]);
    Assert.AreEqual(2,myArray[0,1]);
    Assert.AreEqual(3,myArray[0,2]);
    Assert.AreEqual(4,myArray[1,0]);
    Assert.AreEqual(5,myArray[1,1]);
    Assert.AreEqual(6,myArray[1,2]);
}