C Sharp

Single-Dimensional Array Example

Here's a simple example of declaring a single-dimensional array as a class member, instantiating and filling the array in the constructor, and then using a for loop to iterate through the array, printing out each element: -

using System;
class SingleDimArrayApp
{
    protected int[] numbers;
    SingleDimArrayApp()
    {
        numbers = new int[6];
        for (int i = 0; i < 6; i++)
        {
            numbers[i] = i * i;
        }
    }
    protected void PrintArray()
    {
        for (int i = 0; i < numbers.Length; i++)
        {
            Console.WriteLine("numbers[{0}]={1}", i, numbers[i]);
        }
    }
    public static void Main()
    {
        SingleDimArrayApp app = new SingleDimArrayApp();
        app.PrintArray();
    }
}

Running this example produces the following output: -

numbers[0]=0
numbers[1]=1
numbers[2]=4
numbers[3]=9
numbers[4]=16
numbers[5]=25

In this example, the SingleDimArray.PrintArray method uses the System.Array Length property to determine the number of elements in the array. It's not obvious here, since we have only a single-dimensional array, but the Length property actually returns the number of all the elements in all the dimensions of an array. Therefore, in the case of a two dimensional array of 5 by 4, the Length property would return 9. In the next section, I'll look at multidimensional arrays and how to determine the upper bound of a specific array dimension.