C# Loop Through Arrays
Once your values live in an array, you will often want to visit every element one by one. This is called looping, or iterating, over the array. C# gives you a few ways to do this, and the two most common are the standard for loop and the foreach loop.
Looping With for
A for loop gives you a counter variable that you can use as the index. You start at 0 and keep going while the counter is less than the array's Length. This approach is handy when you need to know the position of each element, or when you want to change values as you go.
for loop over an array
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.Length; i++)
{
Console.WriteLine(i + ": " + cars[i]);
}
// 0: Volvo
// 1: BMW
// 2: Ford
// 3: MazdaLooping With foreach
The foreach loop is shorter and easier to read when you only need the values, not the indexes. It hands you each element in turn and stops automatically at the end. There is no counter to manage, so there is less chance of an off-by-one mistake.
foreach loop over an array
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string car in cars)
{
Console.WriteLine(car);
}Which One Should You Use?
- Use foreach when you just want to read each value in order.
- Use for when you need the index, want to go backwards, or want to skip elements.
- You cannot add or remove elements from an array inside a foreach loop, since the array size is fixed.
Summing numbers with a loop
int[] numbers = {10, 20, 30, 40};
int sum = 0;
foreach (int number in numbers)
{
sum += number;
}
Console.WriteLine("Total: " + sum); // Total: 100