Array Size (Length) in C#

Amal picture Amal · May 16, 2010 · Viewed 267.7k times · Source

How can I determine size of an array (length / number of items) in C#?

Answer

Blair Conrad picture Blair Conrad · May 16, 2010

If it's a one-dimensional array a,

a.Length

will give the number of elements of a.

If b is a rectangular multi-dimensional array (for example, int[,] b = new int[3, 5];)

b.Rank

will give the number of dimensions (2) and

b.GetLength(dimensionIndex)

will get the length of any given dimension (0-based indexing for the dimensions - so b.GetLength(0) is 3 and b.GetLength(1) is 5).

See System.Array documentation for more info.

As @Lucero points out in the comments, there is a concept of a "jagged array", which is really nothing more than a single-dimensional array of (typically single-dimensional) arrays.

For example, one could have the following:

int[][] c = new int[3][];
c[0] = new int[] {1, 2, 3};
c[1] = new int[] {3, 14};
c[2] = new int[] {1, 1, 2, 3, 5, 8, 13};

Note that the 3 members of c all have different lengths. In this case, as before c.Length will indicate the number of elements of c, (3) and c[0].Length, c[1].Length, and c[2].Length will be 3, 2, and 7, respectively.