Problem
I’ve set up an array:
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?
What is the best way for me to get this information?
Asked by Giffyguy
Solution #1
You make use of Array. With the index of the dimension you want to retrieve, use GetLength.
Answered by Reed Copsey
Solution #2
Use GetLength(), rather than Length.
int rowsOrHeight = ary.GetLength(0);
int colsOrWidth = ary.GetLength(1);
Answered by David Yaw
Solution #3
// Two-dimensional GetLength example.
int[,] two = new int[5, 10];
Console.WriteLine(two.GetLength(0)); // Writes 5
Console.WriteLine(two.GetLength(1)); // Writes 10
Answered by Satish Wadkar
Solution #4
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]);
}
Answered by Peter Neorr
Solution #5
ary.GetLength(0)
ary.GetLength(1)
for 2 dimensional array
Answered by Ali Tarhini
Post is based on https://stackoverflow.com/questions/4260207/how-do-you-get-the-width-and-height-of-a-multi-dimensional-array