The Length Property of Arrays


By courtesy of the fact that arrays are class objects, each array has a Length property. This property returns the number of elements originally specified when the array was allocated. The Length property can be used to write clean code. Rather than referring to the original constant or variable used to specify the array size, once the array has been allocated, its Length property may be used instead. For example, consider the following code.

// ArrayLength: The Length Property of Arrays

using System;

class Program
{
    static void Main()
    {
        int[] ai = new int[10];

        for (int i = 0; i < ai.Length; i++)
            ai[i] = i*i;

        for (int i = 0; i < ai.Length; i++)
            Console.WriteLine(ai[i]);
    }
}

An array of 10 integers is allocated. The size is hard coded, however it could have been a variable. In either case, rather than keep referring to the original size, the two loops that follow refer to the Length property to determine the array size. This is good form.

For multidimensional arrays, the Length property returns the total number of elements in the array: which is the product of the individual dimensions of the array.

The Length Property in Jagged Arrays

For jagged arrays, the Length property may be applied to the total array (yielding the total number of subarrays) and the Length property may also be applied to individual subarrays. The next program demonstrates both facilities.

// ArrayLengthJagged: The Length Property of Jagged Arrays

using System;

class Program
{
    static void Main()
    {
        int[][] j = new int[3][];
        j[0] = new int[3];
        j[1] = new int[1];
        j[2] = new int[2];

        int l = 0;

        for (int i = 0; i < j.Length; i++)
            for (int k = 0; k < j[i].Length; k++)
                j[i][k] = l++;

        for (int i = 0; i < j.Length; i++)
        {
            for (int k = 0; k < j[i].Length; k++)
                Console.Write(j[i][k] + ", ");

            Console.WriteLine();
        }
    }
}

The output of this program is as follows.

0, 1, 2, 
3, 
4, 5,