← Back to course: C# from scratch

Arrays: storing several values of the same type

Video coming soon

Until now each variable stored a single value. But many times you need to handle several: the grades of a class, the temperatures of a week, the names of the players. Creating one variable per item is not practical. The most basic solution in C# is the array: a fixed-size collection that stores values of the same type next to each other in memory. Once created, you cannot add or remove elements, but you can change each one of them.

Creating and reading an array

There are two usual ways to create an array. With initial values: int[] numbers = { 4, 8, 15 }; or with new and a size: int[] zeros = new int[5];, where all the elements start with the default value of the type (0 for numbers, false for bool, null for strings). Since C# 12 you can also use brackets: int[] values = [1, 2, 3];. Each element is read with its index in square brackets, starting at 0, and the Length property tells how many there are. The last element is at position Length - 1; you can also use ^1, which means "first from the end".

csharp
int[] numbers = { 4, 8, 15, 16 };
int[] zeros = new int[3];
string[] names = ["Ana", "Luis", "Marta"];

Console.WriteLine(numbers[0]);          // 4
Console.WriteLine(numbers[numbers.Length - 1]); // 16
Console.WriteLine(numbers[^1]);         // 16 (same, from the end)
Console.WriteLine(zeros[1]);            // 0 (default value)

names[1] = "Luis Miguel";               // change an element
Console.WriteLine(names[1]);
Console.WriteLine(names.Length);        // 3

// Console.WriteLine(numbers[4]);       // IndexOutOfRangeException

Trying to read or write at an index outside the range, such as numbers[4] in an array of four elements, causes an IndexOutOfRangeException and the program stops. It is the most frequent error with arrays. The defense is simple: always loop up to Length and, if the index comes from the user, compare it with Length before using it.

Looping over and working with arrays

An array and a for loop are natural partners: the index i goes from 0 to Length - 1 so you can add, find the largest or smallest, or count elements that meet a condition. The Array class offers very handy helpers: Array.Sort sorts the array in place, Array.Reverse reverses it, Array.IndexOf returns the position of a value (or -1 if it does not exist) and Array.Fill fills it with a value. To copy an array, assigning is not enough: int[] b = a; copies nothing, it only makes b point to the same array. Changes in one are seen in the other. Use a.Clone() or the [..a] syntax to get an independent copy.

csharp
int[] grades = { 7, 9, 5, 10, 6 };

int sum = 0;
int max = grades[0];
for (int i = 0; i < grades.Length; i++)
{
    sum += grades[i];
    if (grades[i] > max) max = grades[i];
}
Console.WriteLine($"Sum={sum} Max={max} Average={(double)sum / grades.Length}");
// Sum=37 Max=10 Average=7.4

int[] copy = [..grades];          // independent copy
Array.Sort(grades);
Console.WriteLine(string.Join(", ", grades)); // 5, 6, 7, 9, 10
Console.WriteLine(string.Join(", ", copy));   // 7, 9, 5, 10, 6
Console.WriteLine(Array.IndexOf(grades, 9));  // 3

int[] same = grades;              // NOT a copy
same[0] = 99;
Console.WriteLine(grades[0]);     // 99

int[,] board = new int[2, 3];     // two-dimensional array
board[1, 2] = 7;
Console.WriteLine(board.GetLength(0) + "x" + board.GetLength(1)); // 2x3

Test what you learned

Question 1 of 2

What is the index of the last element of a 5-element array?

✎ My notes

Saved only in this browser. Sign in to keep it in your account.0/5000 characters

← PreviousNext →