Arrays

An array stores a fixed number of values of the same type, one after another, each identified by an index starting at 0. Arrays are the simplest collection in C# and the foundation of many others. This lesson covers creating them, reading and writing elements, looping, and the helper methods in the Array class.

Creating arrays

An array type is written with square brackets after the element type. There are several ways to create one:

C#
int[] scores = new int[4];                  // 4 elements, all 0
string[] days = { "Mon", "Tue", "Wed" };     // array initialiser
double[] temps = new double[] { 18.5, 21.0, 19.2 };
char[] vowels = ['a', 'e', 'i', 'o', 'u'];   // collection expression (C# 12)

Console.WriteLine(scores.Length);
Console.WriteLine(string.Join(", ", scores));
Console.WriteLine(days.Length);
Console.WriteLine(temps[1]);
Console.WriteLine(new string(vowels));
Output
4
0, 0, 0, 0
3
21
aeiou

A new array's elements start at their type's default value: 0, false, or null. Collection expressions — values in square brackets — are the modern, shortest way to write an array's contents; this course uses them from now on.

Reading and writing elements

C#
string[] seats = ["Ana", "Ben", "Chen", "Dara"];

Console.WriteLine(seats[0]);
Console.WriteLine(seats[seats.Length - 1]);

seats[1] = "Bilal";
Console.WriteLine(string.Join(" | ", seats));
Output
Ana
Dara
Ana | Bilal | Chen | Dara

An index outside 0 to Length - 1 throws an exception — C# always checks:

C#
int[] data = [10, 20, 30];
Console.WriteLine(data[3]);
Output
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.

Fixed size

An array's length is set when it's created and never changes. To "add" an element you must create a bigger array — which is why, when the number of items varies, you'll usually use a List<T> (lesson 27) instead.

Looping over arrays

C#
int[] steps = [4200, 8100, 10350, 6020, 12800];

int total = 0;
foreach (int s in steps)
{
    total += s;
}
Console.WriteLine($"Total: {total:N0}");

for (int day = 0; day < steps.Length; day++)
{
    string marker = steps[day] >= 10_000 ? " goal!" : "";
    Console.WriteLine($"Day {day + 1}: {steps[day],6:N0}{marker}");
}
Output
Total: 41,470
Day 1:  4,200
Day 2:  8,100
Day 3: 10,350 goal!
Day 4:  6,020
Day 5: 12,800 goal!

The Array class

Static methods on Array sort, search and copy arrays:

C#
int[] numbers = [42, 7, 19, 3, 25];

Array.Sort(numbers);
Console.WriteLine(string.Join(", ", numbers));

Array.Reverse(numbers);
Console.WriteLine(string.Join(", ", numbers));

Console.WriteLine(Array.IndexOf(numbers, 19));
Console.WriteLine(Array.IndexOf(numbers, 100));
Console.WriteLine(Array.Exists(numbers, n => n > 40));
Console.WriteLine(Array.Find(numbers, n => n < 10));

int[] filled = new int[5];
Array.Fill(filled, 9);
Console.WriteLine(string.Join("", filled));

Array.Resize(ref filled, 7);   // creates a new, longer array
Console.WriteLine(string.Join("", filled));
Output
3, 7, 19, 25, 42
42, 25, 19, 7, 3
2
-1
True
7
99999
9999900

n => n > 40 is a lambda — a small inline function. Lesson 47 explains lambdas; for now read it as "given n, is n greater than 40?".

LINQ helpers

Thanks to LINQ (lesson 49), arrays also have methods such as Sum, Max, Average and Contains:

C#
decimal[] prices = [4.99m, 12.50m, 3.25m, 8.00m];

Console.WriteLine(prices.Sum());
Console.WriteLine(prices.Max());
Console.WriteLine(prices.Min());
Console.WriteLine(prices.Average());
Console.WriteLine(prices.Contains(3.25m));
Console.WriteLine(prices.Count(p => p > 5));
Output
28.74
12.50
3.25
7.185
True
2

Arrays are reference types

Assigning an array to another variable copies the reference, not the elements (as you saw in lesson 7). To get an independent copy, use a collection expression with the spread operator .., or Clone:

C#
int[] original = [1, 2, 3];
int[] alias = original;
int[] copy = [.. original];

alias[0] = 100;
copy[1] = 200;

Console.WriteLine(string.Join(", ", original));
Console.WriteLine(string.Join(", ", copy));
Console.WriteLine(original == alias);
Console.WriteLine(original.SequenceEqual([100, 2, 3]));
Output
100, 2, 3
1, 200, 3
True
True

Note that == on arrays checks whether two variables refer to the same array. To compare contents, use SequenceEqual.

Arrays of other types

Arrays can hold any type, including strings, objects and tuples:

C#
(string Name, int Age)[] people = [("Iris", 34), ("Omar", 27), ("Lena", 41)];

Array.Sort(people, (a, b) => a.Age.CompareTo(b.Age));
foreach (var (name, age) in people)
{
    Console.WriteLine($"{name} ({age})");
}
Output
Omar (27)
Iris (34)
Lena (41)

Try it yourself

Find the highest and lowest temperatures of the week, and which days they fell on.

Try it yourself · Program.cs
Edit the code, copy it into Program.cs and run it with dotnet run Program.cs (.NET 10 or later). How to set up .NET
Output
Hottest: Sun (23.1 °C)
Coldest: Fri (16.5 °C)
Average: 19.8 °C