Arrays in C#

Arrays are indexed lists of variables stored in a single array type variable. For example, you might have an array called friendNames that stores the three names shown above. You can access individual members of this array by specifying their index in square brackets, as shown here:
friendNames[ < index > ]
This index is simply an integer, starting with 0 for the first entry, using 1 for the second, and so on. This means that you can go through the entries using a loop:

int i;
for (i = 0; i &lt; 3; i++)
Console.WriteLine("Name with index of {0}: {1}", i, friendNames[i]);

Arrays have a single base type — that is, individual entries in an array are all of the same type. This friendNames array has a base type of string because it is intended for storing string variables. Array entries are often referred to as elements.

Declaring Arrays

Arrays are declared in the following way:
< baseType > [] < name > ;
Here, < baseType > may be any variable type, including the enumeration and struct types you ’ ve seen in other topics. Arrays must be initialized before you have access to them. You can ’ t just access or assign values to the array elements like this:

int[] myIntArray;
myIntArray[10] = 5;

Arrays can be initialized in two ways. You can either specify the complete contents of the array in a literal form, or you can specify the size of the array and use the new keyword to initialize all array elements.
Specifying an array using literal values simply involves providing a comma – separated list of element values enclosed in curly braces:

int[] myIntArray = {5, 9, 10, 2, 99};

Here, myIntArray has five elements, each with an assigned integer value. The other method requires the following syntax:

int[] myIntArray = new int[5];

Here, you use the new keyword to explicitly initialize the array, and a constant value to define the size. This method results in all the array members being assigned a default value, which is 0 for numeric types. You can also use nonconstant variables for this initialization:

int[] myIntArray = new int[arraySize];

In addition, you can combine these two methods of initialization if you wish:

int[] myIntArray = new int[5] {5, 9, 10, 2, 99};

With this method the sizes must match. You can ’ t, for example, write

int[] myIntArray = new int[10] {5, 9, 10, 2, 99};

Here, the array is defined as having 10 members, but only 5 are defined, so compilation will fail. A side effect of this is that if you define the size using a variable, then that variable must be a constant:

const int arraySize = 5;
int[] myIntArray = new int[arraySize] {5, 9, 10, 2, 99};

If you omit the const keyword, this code will fail. As with other variable types, there is no need to initialize an array on the same line that you declare it. The following is perfectly legal:

int[] myIntArray;
myIntArray = new int[5];

You may also like...