C# Arrays

An array lets you store many values of the same type in a single variable, instead of declaring a separate variable for each value. If you needed to keep track of five student scores, you could create five variables, but that quickly gets messy. An array holds them all together and gives each one a numbered position.

Creating an Array

To declare an array, write the type followed by square brackets. You can create an empty array of a fixed size, or you can fill it with values right away using curly braces. Each value in an array is called an element.

Declaring and initializing arrays

// An array that will hold 4 strings
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

// An empty array of 3 integers (defaults to 0)
int[] scores = new int[3];

Console.WriteLine(cars[0]);   // Volvo
Console.WriteLine(scores[0]); // 0

Accessing Elements

You access an element by its index. Array indexes start at 0, so the first element is at index 0, the second at index 1, and so on. Using an index that is too large will throw an IndexOutOfRangeException at runtime.

Reading and changing elements

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

Console.WriteLine(cars[1]); // BMW

// Change the value at index 0
cars[0] = "Opel";
Console.WriteLine(cars[0]); // Opel

Array Length

Every array has a built-in Length property that tells you how many elements it contains. This is very useful when you loop through an array, because the count comes straight from the array itself.

Using the Length property

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars.Length); // 4
Note: The size of an array is fixed once it is created. If you need a collection that can grow or shrink, look at List<T> instead of a plain array.

Common ways to create arrays

SyntaxMeaning
int[] a = new int[5];Empty array with 5 slots, all set to 0
int[] a = {1, 2, 3};Array with three given values
int[] a = new int[] {1, 2, 3};Same as above, with the type written out

Exercise: C# Arrays

Once a C# array is created with a given length, can that length change?