Visual Studio .NET 2003
This tutorial describes arrays and shows how they work in C#.
Sample Files
See Arrays Sample to download and build the sample files discussed in this tutorial.
Further Reading * Arrays * 12. Arrays * foreach, in * Collection Classes Tutorial
Tutorial
This tutorial is divided into the following sections: * Arrays in General * Declaring Arrays * Initializing Arrays * Accessing Array Members * Arrays are Objects * Using foreach with Arrays
Arrays in General
C# arrays are zero indexed; that is, the array indexes start at zero. Arrays in C# work similarly to how arrays work in most other popular languages There are, however, a few differences that you should be aware of.
When declaring an array, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#.
Copy
int[] table; // not int table[];
Another detail is that the size of the array is not part of its type as it is in the C language. This allows you to declare an array and assign any array of int objects to it, regardless of the array's length.
Copy
int[] numbers; // declare numbers as an int array of any size numbers = new int[10]; // numbers is a 10-element array numbers = new int[20]; // now it's a 20-element array
Declaring Arrays
C# supports single-dimensional arrays, multidimensional arrays (rectangular arrays), and array-of-arrays (jagged arrays). The following examples show how to declare different kinds of arrays:
Single-dimensional arrays:
Copy
int[] numbers;
Multidimensional arrays:
Copy
string[,] names;
Array-of-arrays (jagged):
Copy
byte[][] scores;
Declaring them (as shown above) does not actually create the arrays. In C#, arrays are objects (discussed later in this tutorial) and must be instantiated.