Array Initializers


In the previous averaging example on arrays, the array elements were given values manually. When a fixed number of known values are provided for the elements of the array, another form of syntax is available for array initialization. That syntax is described below.

type[] array-name = {value0, value1, value2, ..., valueN};

The size of the generated array is determined by the number of values in the initializer list. value0 is assigned to array-name[0], value1 is assigned to array-name[1] etc. An explicit call to the new operator is not required in this case. The previous averaging example on arrays can thus be redone as follows.

// Average2 - Averaging an Array of Doubles

using System;

class Arrays
{
    static void Main()
    {
        double[] darray = {  .5, 1.5, 2.5, 3.5, 4.5,
                            5.5, 6.5, 7.5, 8.5, 9.5 };

        double average = 0;

        for (int i = 0; i < darray.Length; i++)
            average += darray[i];

        average /= darray.Length;

        Console.WriteLine("Average = " + average);
    }
}

Although it is not required, the new operator can be used in conjunction with an initializer list as shown below.

double[] darray = new double[] {  .5, 1.5, 2.5, 3.5, 4.5,
                                 5.5, 6.5, 7.5, 8.5, 9.5 };

This form of syntax is useful when assigning a new array to an existing array reference variable - as shown below.

double[] darray;
darray = new double[] {  .5, 1.5, 2.5, 3.5, 4.5,
                        5.5, 6.5, 7.5, 8.5, 9.5 };

Here the declaration of the array reference variable is in one statement and the initialization of that variable is contained in another statement.

It is also possible to explicitly specify the size of the array when initializing the array but the specified size must agree with the number of initializers in the list. An example of this is shown below.

double[] darray = new double[10] {  .5, 1.5, 2.5, 3.5, 4.5,
                                   5.5, 6.5, 7.5, 8.5, 9.5 };

A final point is that array boundaries are enforced by runtime checks. When an array bound is overrun, the exception IndexOutOfRangeException is thrown.