Arrays

C# · Lesson 12 of 31 6 min read Updated

Storing the marks of one student needs one variable. Storing the marks of sixty students in sixty separate variables would be madness. An array holds many values of the same type under one name, and you reach each value by its position, called the index.

In this lesson you will create arrays, read and change their items, loop over them, sort and search them, copy them correctly, and use two-dimensional arrays for grids like a cinema seat map.

Creating and using arrays

An array type is written with square brackets after the item type: int[] is "an array of ints". Since C# 12 the easiest way to create one is a collection expression in square brackets.

C#
int[] marks = [78, 91, 66, 85, 59];

Console.WriteLine(marks.Length);
Console.WriteLine(marks[0]);
Console.WriteLine(marks[^1]);

marks[2] = 70;
Console.WriteLine(string.Join(", ", marks));
Console.WriteLine(marks);

int[] empty = new int[4];
string[] names = new string[3];
Console.WriteLine(string.Join(" ", empty));
Console.WriteLine(names[0] is null);
Output
5
78
59
78, 91, 70, 85, 59
System.Int32[]
0 0 0 0
True

Key facts about arrays:

  • Indexes start at 0, so the last item is at Length - 1. marks[^1] is a shortcut for the last item.
  • You can change an item with marks[2] = 70;, but you cannot change the size of an array once it is created. For a growing collection, use a List<T> (next lesson).
  • new int[4] creates an array of four items filled with the default value: 0 for numbers, false for bool and null for strings and other reference types.
  • Printing an array directly shows only its type name, System.Int32[]. Use string.Join to see the items.

Looping over an array

foreach is the simplest way to visit every item. Use for when you also need the index, as in this week of sales at a Lucknow sweet shop:

C#
int[] sales = [1200, 850, 1430, 990, 1710, 640, 1105];

int total = 0;
int best = sales[0];
int bestDay = 0;

for (int i = 0; i < sales.Length; i++)
{
    total += sales[i];
    if (sales[i] > best)
    {
        best = sales[i];
        bestDay = i;
    }
}

double average = (double)total / sales.Length;
Console.WriteLine($"Total: Rs {total}");
Console.WriteLine($"Average: Rs {average:F2}");
Console.WriteLine($"Best day: day {bestDay + 1} with Rs {best}");
Console.WriteLine($"Quick check: {sales.Sum()}, {sales.Max()}, {sales.Average():F2}");
Output
Total: Rs 7925
Average: Rs 1132.14
Best day: day 5 with Rs 1710
Quick check: 7925, 1710, 1132.14

Writing the loop yourself teaches you how these calculations work. In everyday code, the LINQ methods Sum(), Max(), Min() and Average() in the last line do the same job in one call. Note the cast (double)total: without it, 7925 / 7 would be integer division.

Sorting, searching and slicing

The Array class has static helper methods, and ranges let you take a slice.

C#
string[] cities = ["Pune", "Agra", "Kochi", "Jaipur"];

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

Console.WriteLine(Array.IndexOf(cities, "Kochi"));
Console.WriteLine(Array.IndexOf(cities, "Delhi"));
Console.WriteLine(cities.Contains("Agra"));

string[] firstTwo = cities[..2];
Console.WriteLine(string.Join(", ", firstTwo));

Array.Reverse(cities);
Console.WriteLine(string.Join(", ", cities));
Output
Agra, Jaipur, Kochi, Pune
2
-1
True
Agra, Jaipur
Pune, Kochi, Jaipur, Agra

Array.Sort and Array.Reverse change the array in place. Array.IndexOf returns -1 when the item is missing. A range such as cities[..2] creates a new array containing a copy of those items.

Arrays are reference types

An array variable does not hold the items directly; it holds a reference to the array. Assigning one array variable to another copies the reference, not the items, so both names point to the same array.

C#
int[] original = [10, 20, 30];
int[] sameArray = original;
int[] copy = [.. original];

sameArray[0] = 99;

Console.WriteLine(string.Join(",", original));
Console.WriteLine(string.Join(",", copy));

int[] morning = [5, 8];
int[] evening = [3, 9, 4];
int[] wholeDay = [.. morning, .. evening];
Console.WriteLine(string.Join(",", wholeDay));
Output
99,20,30
10,20,30
5,8,3,9,4

Changing sameArray[0] also changed original, because they are the same array. [.. original] uses the spread element .. to build a new array with copies of the items, so copy is independent. Spread also joins arrays, as wholeDay shows. For the same reason, == on two arrays checks whether they are the same array, not whether they hold the same values.

Two-dimensional and jagged arrays

A two-dimensional (2D) array is a grid with rows and columns, written int[,]. A jagged array, int[][], is an array of arrays where each inner array can have a different length.

C#
int[,] seats = new int[3, 4]; // 3 rows, 4 seats each; 0 = free, 1 = booked
seats[0, 1] = 1;
seats[2, 3] = 1;

for (int row = 0; row < seats.GetLength(0); row++)
{
    for (int col = 0; col < seats.GetLength(1); col++)
    {
        Console.Write(seats[row, col] == 1 ? "X " : ". ");
    }
    Console.WriteLine();
}

int[][] testsPerStudent = [[78, 91], [66, 85, 59], [90]];
foreach (int[] tests in testsPerStudent)
{
    Console.WriteLine($"Tests: {tests.Length}, total: {tests.Sum()}");
}
Output
. X . . 
. . . . 
. . . X 
Tests: 2, total: 169
Tests: 3, total: 210
Tests: 1, total: 90

GetLength(0) gives the number of rows and GetLength(1) the number of columns. For a 2D array, Length is the total number of cells (12 here). Use a 2D array when every row has the same size, like a seat map, and a jagged array when rows differ, like students who took different numbers of tests.

Common mistakes

  • Going past the end. marks[marks.Length] throws IndexOutOfRangeException: Index was outside the bounds of the array. The last index is Length - 1.
  • Expecting an array to grow. Arrays have a fixed size. Use List<T> when items are added or removed.
  • Printing the array itself. You see System.Int32[]; use string.Join.
  • Thinking b = a copies the array. It copies the reference. Use [.. a] or a.ToArray() for a real copy.
  • Comparing arrays with ==. It compares references. Use a.SequenceEqual(b) to compare items.

Key points

  • int[] a = [1, 2, 3]; creates an array; indexes run from 0 to Length - 1.
  • a[^1] is the last item and a[1..3] is a new array with a slice.
  • Arrays have a fixed size; new arrays are filled with default values.
  • Array.Sort, Array.Reverse and Array.IndexOf help with common tasks; LINQ adds Sum, Max and Average.
  • Arrays are reference types; use spread [.. a] to copy or combine them.
  • int[,] is a rectangular grid; int[][] is an array of arrays with different lengths.

Exercise

A Rohtak cricket coach records the runs of six batters: [45, 12, 78, 0, 33, 101]. Write a program that prints the runs in descending order (highest first), the number of batters who scored 30 or more, and the average of the top three scores rounded to one decimal place. Do not change the original array: sort a copy.

Show solution
C#
int[] runs = [45, 12, 78, 0, 33, 101];

int[] sorted = [.. runs];
Array.Sort(sorted);
Array.Reverse(sorted);
Console.WriteLine($"Descending: {string.Join(", ", sorted)}");

int count = 0;
foreach (int r in runs)
{
    if (r >= 30)
    {
        count++;
    }
}
Console.WriteLine($"Scored 30+: {count}");

int[] topThree = sorted[..3];
Console.WriteLine($"Top three average: {topThree.Average():F1}");
Console.WriteLine($"Original: {string.Join(", ", runs)}");
Output
Descending: 101, 78, 45, 33, 12, 0
Scored 30+: 4
Top three average: 74.7
Original: 45, 12, 78, 0, 33, 101

Sorting then reversing gives descending order. The top three are 101, 78 and 45, whose average is 74.666..., shown as 74.7. Because sorted is a spread copy, the original array keeps its order.

Quick Quiz

1. What is the index of the last item in an array of length 8?

2. What does new string[3] contain?

3. After int[] a = [1, 2]; int[] b = a; b[0] = 5;, what is a[0]?

4. Which type is best for a cinema hall where every row has exactly 20 seats?

Learn C# with a mentor

Free lessons get you started. Our Programming & Software Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call