CSharp/C# Tutorial - C# Array






An array represents a fixed number of variables of a particular type.

An array is created with square brackets after the element type.

For example:


char[] letterArray = new char[5]; // Declare an array of 5 characters 

We can use square brackets to index the array, and access a particular element by position:


letterArray[0] = 'a'; 
letterArray[1] = 'e'; 
letterArray[2] = 'i'; 
letterArray[3] = 'o'; 
letterArray[4] = 'u'; 
Console.WriteLine (letterArray[1]); // e 

We can use a for loop statement to iterate through each element in the array.


for (int i = 0; i < letterArray.Length; i++) {
    Console.Write (letterArray[i]); // aeiou 
}

The Length property of an array returns the number of elements in the array.

Once an array has been created, its length cannot be changed.

An array initialization expression can declare and populate an array in a single step:


char[] letterArray = new char[] {'a','e','i','o','u'}; 

or simply:


char[] letterArray = {'a','e','i','o','u'}; 

All arrays inherit from the System.Array class, providing common services for all arrays.





Default Element Initialization

Creating an array always preinitializes the elements with default values.

For example, consider creating an array of integers. Since int is a value type, this allocates 1,000 integers.

The default value for each element will be 0:


int[] a = new int[1000]; 
Console.Write (a[123]); // 0 

Value types versus reference types

When the element type is a value type, each element value is allocated as part of the array.

For example:


struct Point { 
  public int X, Y; 
} 

Point[] a = new Point[1000]; 
int x = a[500].X; // 0 

If Point is a class, creating the array would have only allocated 10 null references:


class Point { 
  public int X, Y; 
} 

Point[] a = new Point[10]; 
int x = a[5].X; // Runtime error, NullReferenceException 

To avoid this error, explicitly instantiate Point value after instantiating the array:


Point[] a = new Point[10]; 
for (int i = 0; i < a.Length; i++){ // Iterate i from 0 to 9
    a[i] = new Point();             // Set array element i with new point 
}

An array itself is always a reference type object, regardless of the element type.

For instance, the following is legal:


int[] myArray = null;