Novice Developer
Novice Developer

Reputation: 4759

What is the difference between Array.GetLength() and Array.Length?

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

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

Upvotes: 56

Views: 96552

Answers (5)

K_Unit
K_Unit

Reputation: 111

The .Length property returns the number of elements in an array, whether it be one dimensional or multidimensional. That is a 2x6 array will have length of 12.

The .GetLength(0) method returns number of elements in the row direction in a multidimensional array. For a 2x6 array that is 2.

The .GetLength(1) method returns number of elements in the column direction in a multidimensional array. For a 2x6 array that is 6.

These do not return an actual element value, as stated by the chosen answer above.

Upvotes: 10

Vineetha Mathew
Vineetha Mathew

Reputation: 3

In mathematical term, we call as m rows and n columns, so the results is product of m*n for a two dimensional array. In this case GetLength(0) = m rows and GetLength(1)= n columns. For e.g see below example

string[,] stocks ={{"RELIND","Reliance Industries","1006.30"},{"TATMOB","Tata Mobiles","504.10"},{"ALST","Allstate","800.00"}, {"GE","GE Motors","810.00"}
};

The stocks arrays return GetLength(0)= 4 and GetLength(1)=3 and length =12

Upvotes: 0

Jason Williams
Jason Williams

Reputation: 57952

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.

Upvotes: 4

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422320

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

Upvotes: 96

Henk Holterman
Henk Holterman

Reputation: 273854

For 1-dimensional arrays Length and GetLength(0) are exactly the same.

For arrays of higher rank Length is the product of all GetLength(0..Rank-1) values, in other words it is always the total number of fields.

Upvotes: 16

Related Questions