268

I have an array defined:

int [,] ary;
// ...
int nArea = ary.Length; // x*y or total area

This is all well and good, but I need to know how wide this array is in the x and y dimensions individually. Namely, ary.Length might return 12 - but does that mean the array is 4 high and 3 wide, or 6 high and 2 wide?

How can I retrieve this information?

Giffyguy
  • 20,378
  • 34
  • 97
  • 168

6 Answers6

370

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

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 150
    `.Rank` for the number of dimensions. In the case this is 2, `.GetLength(0)` for the number of rows, `.GetLength(1)` for the number of columns. – Colonel Panic Nov 27 '12 at 11:53
192

Use GetLength(), rather than Length.

int rowsOrHeight = ary.GetLength(0);
int colsOrWidth = ary.GetLength(1);
juFo
  • 17,849
  • 10
  • 105
  • 142
David Yaw
  • 27,383
  • 4
  • 60
  • 93
70
// Two-dimensional GetLength example.
int[,] two = new int[5, 10];
Console.WriteLine(two.GetLength(0)); // Writes 5
Console.WriteLine(two.GetLength(1)); // Writes 10
Jens Erat
  • 37,523
  • 16
  • 80
  • 96
Satish Wadkar
  • 709
  • 5
  • 3
35

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]);
}
Peter Neorr
  • 449
  • 4
  • 8
29
ary.GetLength(0) 
ary.GetLength(1)

for 2 dimensional array

Ali Tarhini
  • 5,278
  • 6
  • 41
  • 66
6

You could also consider using getting the indexes of last elements in each specified dimensions using this as following;

int x = ary.GetUpperBound(0);
int y = ary.GetUpperBound(1);

Keep in mind that this gets the value of index as 0-based.

zalky
  • 659
  • 1
  • 7
  • 12