C# Arrays
Storing multiple values in one variable.
C# Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
To declare an array, define the variable type with square brackets:
string[] cars;
We have now declared a variable that holds an array of strings. To insert values to it, use an array literal - place the values in a comma-separated list, inside curly braces:
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Access the Elements of an Array
You access an array element by referring to the index number.
This statement accesses the value of the first element in cars:
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars[0]); // Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Array Length
To find out how many elements an array has, use the Length property:
Console.WriteLine(cars.Length);
Examples
Create and Access Array
Outputs the first element.
using System;
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars[0]);
}
}Change Array Element
Changing the first element.
using System;
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
Console.WriteLine(cars[0]);
}
}Array Length
Getting the number of elements.
using System;
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars.Length);
}
}Loop Through an Array
Using a for loop.
using System;
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.Length; i++)
{
Console.WriteLine(cars[i]);
}
}
}