C# Arrays

C# Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. They are incredibly useful for managing lists of similar data.


Declaring an Array

To declare an array, define the variable type with square brackets [].

// Create an array of strings
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

// Create an array of integers int[] myNum = {10, 20, 30, 40};


Accessing Array Elements

You access an array element by referring to its index number. In C# (and almost all programming languages), array indexes start at 0. Therefore, [0] is the first element, [1] is the second element, and so on.

Accessing and Changing Arrays

using System;

class Program { static void Main() { string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; // Access the first item Console.WriteLine(cars[0]); // Outputs Volvo // Change an item cars[0] = "Opel"; Console.WriteLine(cars[0]); // Now outputs Opel } }


Array Length and Sorting

To find out how many elements an array has, use the Length property. To sort an array alphabetically or numerically, use the Array.Sort() method from the System namespace.

Array Methods

using System;

class Program { static void Main() { string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; Console.WriteLine("Length of array: " + cars.Length); Array.Sort(cars); foreach (string i in cars) { Console.WriteLine(i); // Outputs BMW, Ford, Mazda, Volvo in order! } } }


Exercise

?

What is the index of the first element in an array?