TExcelTAD
Home › C# › C# Arrays

C# Arrays

An array stores a fixed number of values of the same type in a single variable. Instead of score1, score2, score3… you write one scores array and access each element by its index, starting at 0.

Creating arrays

There are several equivalent ways to create an array:

csharp · try it yourself
using System;

string[] colors = { "red", "green", "blue" };      // initializer
int[] primes = new int[] { 2, 3, 5, 7, 11 };       // explicit new
double[] readings = new double[4];                 // 4 elements, all 0
int[] squares = [1, 4, 9, 16];                     // collection expression (C# 12)

Console.WriteLine(colors[0]);
Console.WriteLine(primes[4]);
Console.WriteLine(readings[2]);
Console.WriteLine(squares.Length);
red
11
0
4

Elements of a new array get the default value of their type: 0 for numbers, false for bool, '\0' for char, and null for strings and other reference types.

Reading and changing elements

Use array[index] to read or write an element. Length tells you how many elements there are, so the last index is Length - 1 — or simply ^1.

csharp · try it yourself
using System;

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

cars[0] = "Opel";
Console.WriteLine(cars[0]);
Console.WriteLine(cars[cars.Length - 1]);
Console.WriteLine(cars[^1]);
Console.WriteLine(string.Join(", ", cars[1..3]));
Opel
Mazda
Mazda
BMW, Ford

Accessing an index outside 0 .. Length-1 throws an IndexOutOfRangeException at run time. An array's size is fixed once created; if you need to add and remove elements, use a List<T> (see the Collections lesson).

Looping through an array

csharp · try it yourself
using System;

int[] marks = { 72, 85, 90, 64, 78 };

for (int i = 0; i < marks.Length; i++)
    Console.WriteLine(
quot;Student {i}: {marks[i]}"); int sum = 0; foreach (int m in marks) sum += m; Console.WriteLine(
quot;Average: {(double)sum / marks.Length}");
Student 0: 72
Student 1: 85
Student 2: 90
Student 3: 64
Student 4: 78
Average: 77.8

The Array class helpers

The static System.Array class provides methods for sorting, searching and copying:

Method Description
Array.Sort(arr) Sorts the array in place (ascending)
Array.Reverse(arr) Reverses the order in place
Array.IndexOf(arr, value) Index of the first match, or -1
Array.Exists(arr, predicate) true if any element matches
Array.Fill(arr, value) Sets every element to value
Array.Copy(src, dest, n) Copies n elements
Array.Resize(ref arr, n) Creates a resized copy and assigns it
csharp · try it yourself
using System;

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));

string[] names = { "Mia", "ben", "Ava", "carl" };
Array.Sort(names, StringComparer.OrdinalIgnoreCase);
Console.WriteLine(string.Join(", ", names));
3 7 19 25 42
42 25 19 7 3
2
-1
True
Ava, ben, carl, Mia

The n => n > 40 part is a lambda — a small inline function. You will meet lambdas properly in a later lesson.

Arrays are reference types

An array variable holds a reference to the array. Assigning it to another variable does not copy the elements — both variables point to the same array.

csharp · try it yourself
using System;

int[] original = { 1, 2, 3 };
int[] alias = original;
int[] copy = (int[])original.Clone();

alias[0] = 99;
Console.WriteLine(original[0]);   // changed through alias
Console.WriteLine(copy[0]);       // the clone is independent
99
1

Tip: LINQ (covered later) adds many more operations to arrays: numbers.Max(), numbers.Sum(), numbers.Where(n => n > 10) and so on.

Test yourself

What is the index of the last element of int[] a = new int[8];?

  1. 8
  2. 7
  3. 0
  4. -1

What are the elements of new bool[3]?

  1. true, true, true
  2. false, false, false
  3. null, null, null
  4. Undefined

What does Array.IndexOf(arr, x) return when x is not found?

  1. 0
  2. null
  3. -1
  4. It throws an exception