Arrays let you store multiple values of the same type in a single variable. Instead of creating 10 separate variables for 10 students, you can create one array that holds all 10. Much cleaner.
Creating Arrays
// Method 1: specifying the size
int[] scores = new int[5];
// Method 2: providing values directly
string[] fruits = { "apple", "banana", "mango", "orange" };
// Method 3: explicit syntax
double[] prices = new double[] { 19.99, 29.99, 39.99 };
Once an array is created, its size is fixed. You cannot add or remove elements.
If you need a collection that can grow and shrink, use a List instead
(we will cover that next).
Accessing Array Elements
You access elements by their index โ a number that represents their position. Arrays are zero-indexed, meaning the first element is at index 0:
string[] colors = { "red", "green", "blue", "yellow" };
Console.WriteLine(colors[0]); // red
Console.WriteLine(colors[1]); // green
Console.WriteLine(colors[2]); // blue
Console.WriteLine(colors[3]); // yellow
// Modifying an element
colors[1] = "emerald";
Console.WriteLine(colors[1]); // emerald
If you try to access an index that does not exist (like colors[4]), you will
get an IndexOutOfRangeException. This is one of the most common errors
in programming, so always be careful with your indexes.
Finding the Length
string[] cities = { "Kano", "Lagos", "Abuja" };
Console.WriteLine(cities.Length); // 3
// Looping through all elements
for (int i = 0; i < cities.Length; i++)
{
Console.WriteLine(cities[i]);
}
The .Length property tells you how many elements are in the array. Use it
in your loop condition to avoid going out of bounds.
Looping with foreach
If you do not need the index, foreach is cleaner:
int[] numbers = { 10, 20, 30, 40, 50 };
foreach (int num in numbers)
{
Console.Write(num + " ");
}
// Output: 10 20 30 40 50
Useful Array Methods
int[] data = { 5, 3, 8, 1, 9, 2 };
Array.Sort(data); // Sorts the array: 1 2 3 5 8 9
Array.Reverse(data); // Reverses it: 9 8 5 3 2 1
int index = Array.IndexOf(data, 5); // Finds index of value 5
Console.WriteLine(data.Min()); // 1
Console.WriteLine(data.Max()); // 9
Console.WriteLine(data.Sum()); // 28
These built-in methods save you from writing a lot of common logic yourself. Use them.