C# Array Length
Description
The Length
property of an array returns the number of elements in the array.
Once an array has been created, its length cannot be changed.
Syntax
Here is the syntax we can use to access array length property.
arrayVariable.Length;
Example
The following code uses the array length property to reference the last element in an array.
using System;/*from w ww . j a va 2 s . co m*/
class MainClass
{
static void Main()
{
int[] arr = new int[] { 15, 20, 5, 25, 10 };
Console.WriteLine(arr[arr.Length-1]);
}
}
The code above generates the following result.
Example 2
using System;/*w ww.ja v a 2 s . c o m*/
class MainClass
{
static void Main()
{
int[] arr = new int[] { 15, 20, 5, 25, 10 };
Console.WriteLine("GetLength(0) = {0}", arr.GetLength(0));
}
}
The code above generates the following result.
Example 3
The following code uses the GetLength()
method to
get number of elements in each dimension of the
two dimensional array.
using System;//from w w w . ja va 2 s . com
class MainClass
{
public static void Main()
{
string[,] names = {
{"J", "M", "P"},
{"S", "E", "S"},
{"C", "A", "W"},
{"G", "P", "J"},
};
int numberOfRows = names.GetLength(0);
int numberOfColumns = names.GetLength(1);
Console.WriteLine("Number of rows = " + numberOfRows);
Console.WriteLine("Number of columns = " + numberOfColumns);
}
}
The code above generates the following result.