Lesson 23 +10 XP

C# Arrays

An array stores multiple values of the same type in a single variable, accessible by index.

Declaring an array

There are several ways to declare and fill an array:


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

You can also declare the size first and fill it later:


csharp
string[] cars = new string[4];
cars[0] = "Volvo";

Or declare, size, and fill in one go:


csharp
string[] cars = new string[] { "Volvo", "BMW" };

Access an element

Indexes start at 0. Use square brackets to read an element:


csharp

### Console.WriteLine(cars[0]);   // Volvo

Change an element


csharp
cars[0] = "Opel";

### Console.WriteLine(cars[0]);   // Opel

Array length

.Length gives the number of elements:


csharp

### Console.WriteLine(cars.Length);   // 4

Loop through an array


csharp
string[] cars = { "Volvo", "BMW", "Ford" };
foreach (string car in cars)
{

### Console.WriteLine(car);
}

Sort an array

Array.Sort() sorts alphabetically or numerically:


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

### Array.Sort(cars);
foreach (string car in cars)
{

### Console.WriteLine(car);   // BMW, Ford, Volvo
}

TL;DR

  • type[] name = { ... }; declares an array.
  • Indexes start at 0.
  • .Length gives the element count.
  • foreach loops through arrays; Array.Sort sorts them.