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.