All about Arrays in C#—Accessing Array Elements
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Articles |
| C# Articles |
| © 2006 Christian Gross |
Accessing Array Elements
An array element is accessed using an integer value as an index into the array.
- Each dimension uses 0-based indexing.
- The index is placed between square brackets following the array name.
The following code shows examples of declaring, writing to, and reading from a one- dimensional and a two-dimensional array:
int[] intArr1 = new int[15]; // 1-D example intArr1[2] = 10; // Write to element 2 of the array. int var1 = intArr1[2]; // Read from element 2 of the array. int[,] intArr2 = new int[5,10]; // 2-D example intArr2[2,3] = 7; // Write to the array. int var2 = intArr2[2,3]; // Read from the array.
The following code shows the full process of creating and accessing a one-dimensional array:
int[] myIntArray; // Declare the array. myIntArray = new int[4]; // Instantiate the array. for( int i=0; i<4; i++ ) // Set the values. myIntArray[i] = i*10; // Read and display the values of each element. for( int i=0; i<4; i++ ) Console.WriteLine("Value of element {0} = {1}", i, myIntArray[i]);
This code produces the following output:
Value of element 0 is 0
Value of element 1 is 10
Value of element 2 is 20
Value of element 3 is 30
|

