Arrays

Arrays

Arrays

An array is a construct that contains a fixed number of variables, which can also be referred to as elements. In memory, an array is always stored together, by doing this improves access efficiency.

An array can only store variables of one type and are available for nearly all types. An array is denoted using square brackets.

For example:

string[] cars = new string[5];
cars[0] = "Red car";
cars[1] = "Blue car";
cars[2] = "Green car";
cars[3] = "Yellow car";
cars[4] = "White car";
Console.WriteLine(cars[2]); //Outputs Green car

The index for an array always starts at 0 and will go up to n – 1, where n is the total number of elements.

Arrays have a length member value that will return the total number of elements in that array as an integer. This member value can be useful when defining a for loop which needs to access each element of the array.

string[] cars = {"Red", "Blue", "Green", "Yellow", "White"};
Console.WriteLine(cars.Length); //Outputs 5 
Car Array in csharp

Once initially set, the length of an array cannot change in execution. In a later tutorial, we will go into detail about some data structures that allow for dynamic sizing.

Although the size of an array can not be changed, the value stored in an element can be changed. For example:

    string[] cars = {"Red", "Blue", "Green", "Yellow", "White"};
    Console.WriteLine(cars[1]); //outputs Blue

    cars[1] = "Purple";
    Console.WriteLine(cars[1]); //outputs Purple

Default Values for Array Elements

If you create an array without specifying the default values for elements, a default value will be chosen. For value types, the default value will be the same as zeroing all of the memory associated with that array. For example, if an array of 50 integers was to be defined without initial values, the array would contain 50 zeros.

If reference types are being used then the reference to each object will be stored in the element. If no object is specified then a null reference is stored in its place.

Multidimensional Arrays

Multidimensional arrays are a way of representing more than one dimension in an array, you might want to do this to satisfy complex data.

They can be declared using commas to separate each dimension:

int[,] doubles = new int[2,2];

int[,] doubles = new int[,]
{
   {2,4},
   {4,8}
}

Jagged Arrays

Jagged arrays have a special property that allows for the inner arrays of multidimensional arrays to be of different sizes.

Jagged arrays are declared using successive brackets.

int[][] doubles = new int[][]
{
    new int[] {1,2,4,8,16},
    new int[] {32},
    new int[] {64,128,256,512,1024,2048,4096}
};

Console.WriteLine(doubles[0][1]); //Outputs 2

Array Bounds

If an invalid index is used to try and access an element in an array, then the runtime will throw an IndexOutOfRange Exception.