views:

513

answers:

2

How do you use the Array.GetLength function in C#?

What is the difference between the Length property and the GetLength function?

+16  A: 

GetLength takes an integer that specifies the dimension of the array that you're querying and returns its length. Length property returns the total number of items in an array:

int[,,] a = new int[10,11,12];
Console.WriteLine(a.Length);           // 1320
Console.WriteLine(a.GetLength(0));     // 10
Console.WriteLine(a.GetLength(1));     // 11
Console.WriteLine(a.GetLength(2));     // 12
Mehrdad Afshari
And on one-dimensional arrays `Length` will return the same value as `GetLength(0)`.
0xA3
Why is a.GetLength(2) 11 and not 12?
Mike Pateras
@Mike: Cause 1 and 2 are a single key away.
Mehrdad Afshari
+2  A: 

GetLength returns the length of a specified dimension of a mulit-dimensional array.

Length returns the sum of the total number of elements in all the dimensions.

  • For a single-dimensional array, Length == GetLength(0)
  • For a two-dimensional array, Length == GetLength(0) * GetLength(1)

etc.

Jason Williams
Not quite true: Two dimensional arrays: Length = GetLength(0) * GetLength(1)
Mehrdad Afshari
That's a clever typo! How did I manage to transpose + and * ?! (fixed)
Jason Williams