Skip to content

Beginner · Arrays, strings and null · topic 10 of 43 · 30 min

Arrays: one name, many values

Explanation

An array stores a fixed number of values of the same type under one name. You reach each value by its index, starting at 0, so the last one is at Length - 1 (or ^1). C# also has 2D arrays for grids, jagged arrays (arrays of arrays), ranges like arr[1..3], and helpers such as Array.Sort.

Why arrays?

Storing the marks of 60 students in 60 separate variables would be painful. An array is one variable that holds many values of the same type, side by side in memory. You loop over it, sort it and pass it to methods as one thing.

Think of it like this: An array is like a row of numbered lockers at a railway station. Every locker is the same size (same type), the row has a fixed number of lockers (fixed length), and you open one by its number. The first locker is number 0.

Creating arrays

csharp
int[] marks = new int[5];                   // 5 ints, all 0 at first
string[] days = { "Mon", "Tue", "Wed" };     // filled straight away
double[] prices = new double[] { 9.5, 20.0 };
int[] scores = [70, 85, 90];                 // collection expression, C# 12+
The type with [] means "array of". new int[5] fills it with the default value: 0 for numbers, false for bool, null for strings.

Reading and writing by index

csharp
int[] marks = { 78, 92, 65, 88 };
Console.WriteLine(marks[0]);         // 78 (first)
Console.WriteLine(marks.Length);     // 4
Console.WriteLine(marks[marks.Length - 1]);  // 88 (last)
Console.WriteLine(marks[^1]);        // 88 (^1 = first from the end)
marks[2] = 70;                       // change the third value
Indexes run from 0 to Length - 1.
Careful: marks[4] on a 4-item array throws IndexOutOfRangeException at run time. The compiler cannot catch it. Always loop with i < marks.Length.

Ranges: slicing an array (C# 8 and later)

csharp
int[] n = { 10, 20, 30, 40, 50 };
int[] middle = n[1..4];    // 20, 30, 40 (end is NOT included)
int[] firstTwo = n[..2];   // 10, 20
int[] lastTwo = n[^2..];   // 40, 50
Console.WriteLine(string.Join(", ", middle));
start..end includes start and stops before end. For arrays, a range makes a NEW array (a copy).

Looping and printing

csharp
int[] marks = { 78, 92, 65, 88 };
int total = 0;
foreach (int m in marks) total += m;
Console.WriteLine($"Average: {(double)total / marks.Length}");  // 80.75

Console.WriteLine(marks);                     // System.Int32[]
Console.WriteLine(string.Join(", ", marks));  // 78, 92, 65, 88
Printing an array directly shows only its type name. Use string.Join to show the values.

Useful Array methods

csharp
int[] marks = { 78, 92, 65, 88 };
Array.Sort(marks);                            // 65, 78, 88, 92 (changes the array)
Array.Reverse(marks);                         // 92, 88, 78, 65
int pos = Array.IndexOf(marks, 78);           // 2
int missing = Array.IndexOf(marks, 100);      // -1 means "not found"
Console.WriteLine($"{pos} {missing}");
Array.Sort and Array.Reverse change the array in place.

Arrays are reference types

An array variable does not hold the values themselves; it holds a reference, an arrow pointing to the array in memory. Copying the variable copies the arrow, not the array. Both names then point to the same lockers.

csharp
int[] a = { 1, 2, 3 };
int[] b = a;          // same array, two names
b[0] = 99;
Console.WriteLine(a[0]);     // 99
int[] c = (int[])a.Clone();  // a real copy
c[1] = 0;
Console.WriteLine(a[1]);     // 2
Use Clone() (or a range like a[..]) when you need a separate copy.

2D arrays: grids

csharp
// 3 rows x 4 seats in a small cinema; 1 = booked
int[,] seats = new int[3, 4];
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();
}
A rectangular 2D array uses [row, col]. GetLength(0) is the number of rows and GetLength(1) the number of columns. Length is the total: 12.

Jagged arrays: rows of different lengths

csharp
// Marks of 3 students; each took a different number of tests
int[][] tests = new int[3][];
tests[0] = new[] { 80, 75 };
tests[1] = new[] { 90, 85, 70 };
tests[2] = new[] { 60 };
Console.WriteLine(tests[1][2]);       // 70
Console.WriteLine(tests[2].Length);   // 1
A jagged array is an array of arrays: int[][]. Each inner array can have its own length.

Common mistakes and fixes

  • Starting the count at 1: the first item is [0]. The last is [Length - 1] or [^1].
  • Expecting an array to grow: arrays have a fixed size. When you need to add and remove items, use List<T> (module 6).
  • Using a jagged array's inner array before creating it: tests[0][0] when tests[0] is null throws NullReferenceException.
  • Mixing up [1..3]: it gives items 1 and 2 only. The end index is not included.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Arrays: one name, many values · 1/7

Arrays

In this lesson you will store many values in one array.

Prefer a video by a teacher? Find free videos on “C# arrays tutorial index range 2D jagged array beginners” on YouTube ↗

In real life: Class topper and average for a school report

A school in Lucknow keeps the maths marks of a section in an array. The teacher needs the class average, the highest mark and the top three marks for the notice board.

csharp
int[] maths = { 67, 88, 92, 45, 79, 95, 81 };

int total = 0, highest = maths[0];
foreach (int m in maths)
{
    total += m;
    if (m > highest) highest = m;
}

int[] sorted = (int[])maths.Clone();
Array.Sort(sorted);
int[] topThree = sorted[^3..];

Console.WriteLine($"Average: {(double)total / maths.Length:F1}");
Console.WriteLine($"Highest: {highest}");
Console.WriteLine($"Top three: {string.Join(", ", topThree)}");
Shows Average: 78.1, Highest: 95, Top three: 88, 92, 95. Sorting a clone keeps the original order safe.

Practice (0/4 done)

Task 1 · Question

int[] a = { 5, 10, 15, 20 }; What is a[2]?

Task 2 · Question

int[] a = { 5, 10, 15, 20 }; What does string.Join(" ", a[1..3]) give?

Task 3 · Question

What does this print? int[] a = { 1, 2, 3 }; int[] b = a; b[2] = 30; Console.WriteLine(a[2]);

Task 4 · Practice

Daily temperatures for a week in Jaipur are 31, 34, 36, 33, 38, 35, 32. Write a program that prints the hottest day number (1 to 7), the average with one decimal, and how many days were above 34.

Quick quiz

Question 1

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

Question 2

2.What does new int[3] contain at first?

Question 3

3.What does Array.IndexOf return when the value is not found?

Question 4

4.int[,] g = new int[3, 4]; What is g.Length?

Question 5

5.What does Console.WriteLine(new int[] { 1, 2 }); print?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

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

Answer: 7

Indexes go from 0 to Length - 1.

What does new int[3] contain at first?

Answer: 0, 0, 0

Arrays are filled with the type's default value: 0 for int.

What does Array.IndexOf return when the value is not found?

Answer: -1

-1 means "not found" for IndexOf methods.

int[,] g = new int[3, 4]; What is g.Length?

Answer: 12

Length of a 2D array is the total number of cells: 3 x 4 = 12.

What does Console.WriteLine(new int[] { 1, 2 }); print?

Answer: System.Int32[]

Arrays do not print their contents; you see the type name. Use string.Join.

In a function parameter for a 2D int array with 4 columns, which is valid?Related

Answer: int g[][4]

All dimensions except the first are required.

From 2D arrays and classic array algorithms

How do you get the length of an array arr?Related

Answer: arr.length

For arrays, length is a field (no brackets). Strings use length().

From Arrays

In int[][] t = new int[3][5]; what is t.length and t[0].length?Related

Answer: 3 and 5

First dimension rows (3), second columns (5).

From Two-dimensional arrays and array algorithms

What is the index of the LAST element of an array of size 10?Related

Answer: 9

Indexes run from 0 to size - 1.

From Arrays, std::array and a first look at std::vector

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Arrays, strings and null” before its exam: Strings: methods, interpolation, verbatim and raw strings, StringBuilder and string performance, null, nullable types and null-safe operators.
  2. Module 3 exam: Arrays, strings and null · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Classes and objects. 43 topics left in the course before the final exam.

← Previous: Parameters in depth: optional, named, ref, out, params, overloading