Looping over Arrays
Looping over an array means visiting each element one at a time. C# gives you two main ways to do it.
Option 1: For Loops
A for loop uses a counter as the index, running from 0 up to Length - 1:
string[] colors = {"red", "green", "blue", "purple", "pink"};
for (int i = 0; i < colors.Length; i++)
{
Console.WriteLine($"I love the color {colors[i]}");
}
Because you have the index, you can also change elements:
colors[i] = "orange"; // ✅ Allowed
Option 2: Foreach Loops
A foreach loop hands you each element directly, without an index:
foreach (string color in colors)
{
Console.WriteLine($"I love the color {color}");
}
The general form is:
foreach (type item in arrayName)
{
// use item here
}
itemcan have any name. By convention, use the singular of the array name:colors→color,students→student.itemis read-only.
SOOOO, unlike in for loops, assigning to it won't compile:
color = "orange"; // ❌ Error
Which one should you use?
Use foreach when… | Use for when… |
|---|---|
| You only need to read each element | You need to change elements |
| You don't care about the position | You need the index |
| You want the cleanest code | You want to go backwards, skip elements or stop part way |