Array.GetLength Method (Int32)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Gets a 32-bit integer that represents the number of elements in the specified dimension of the Array.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

public int GetLength(
	int dimension


Type: System.Int32

A zero-based dimension of the Array whose length needs to be determined.

Return Value

Type: System.Int32

A 32-bit integer that represents the number of elements in the specified dimension.

Exception Condition

dimension is less than zero.


dimension is equal to or greater than Rank.

An example of GetLength is GetLength(0), which returns the number of elements in the first dimension of the Array.

This method is an O(1) operation.

The following example shows how to use GetLength to display the dimensions of two arrays with different ranks.

using System;

public class SamplesArray
    public static void Main()
        // make a single dimension array
        Array MyArray1 = Array.CreateInstance(typeof(int), 5);

        // make a 3 dimensional array
        Array MyArray2 = Array.CreateInstance(typeof(int), 5, 3, 2);

        // make an array container
        Array BossArray = Array.CreateInstance(typeof(Array), 2);
        BossArray.SetValue(MyArray1, 0);
        BossArray.SetValue(MyArray2, 1);

        int i = 0, j, rank;
        foreach (Array anArray in BossArray)
            rank = anArray.Rank;
            if (rank > 1)
                Console.WriteLine("Lengths of {0:d} dimension array[{1:d}]", rank, i);
                // show the lengths of each dimension
                for (j = 0; j < rank; j++)
                    Console.WriteLine("    Length of dimension({0:d}) = {1:d}", j, anArray.GetLength(j));
                Console.WriteLine("Lengths of single dimension array[{0:d}]", i);
            // show the total length of the entire array or all dimensions
            Console.WriteLine("    Total length of the array = {0:d}", anArray.Length);

This code produces the following output:

Lengths of single dimension array[0]
    Total length of the array = 5

Lengths of 3 dimension array[1]
    Length of dimension(0) = 5
    Length of dimension(1) = 3
    Length of dimension(2) = 2
    Total length of the array = 30

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top