This post will discuss how to find the length of an array in C#.

1. Using Array.Length Property

The standard solution to find the length of an array is using the Array.Length property. It returns the total number of elements contained in an array. If the array is empty, it returns zero. The following example demonstrates it:

Download  Run Code

Output:

Length is 5

 
For multi-dimensional arrays, the Array.Length property returns the total number of elements in all the dimensions. In other words, it returns the sum of the total number of elements in each dimension of a multidimensional array.

Download  Run Code

Output:

Length is 6

 
In C#, a jagged array can be of different dimensions and sizes. For a jagged array, the Length property will indicate the number of dimensions in the array. For example,

Download  Run Code

Output:

array.Length is 3
array[0].Length is 2
array[1].Length is 3
array[2].Length is 4

2. Using Array.GetLength(Int32) Method

Alternatively, you can use the Array.GetLength() method to get the length of a single-dimensional array. The idea is to pass the zero dimension to the GetLength method to determine the total number of elements in the first dimension of the array.

Download  Run Code

Output:

Length is 5

 
If the array is multidimensional, the Array.GetLength() method returns the total number of elements in the specified dimension of the multidimensional array.

Download  Run Code

Output:

Length is 2

3. Using Array.Rank Property

If you need the number of dimensions of an array instead of the number of elements, use Array.Rank Property. It returns 1 for a one-dimensional array and jagged array (an array of arrays), 2 for a two-dimensional array, and so on.

Download  Run Code

Output:

Rank is 2

4. Using foreach

Another possible, but less recommended, option is to manually count the number of elements in the array. The following example shows how to use a foreach loop and a counter variable to achieve the same.

Download  Run Code

Output:

Length is 5

That’s all about finding the length of an array in C#.