Lesson 23 +10 XP

C# Arrays

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:

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

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

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

Or declare, size, and fill in one go:

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

Access an element

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

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

Change an element

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

Array length

.Length gives the number of elements:

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

Loop through an array

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

Sort an array

Array.Sort() sorts alphabetically or numerically:

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.