Foreach Loop
Visit every element of an array without an index using C#'s foreach loop, and leave a loop early with break or skip ahead with continue.
Apprentice · C# · Updated
After this lesson you can
- Visit every element of an array with a foreach loop
- Stop a loop early with break, or skip to the next iteration with continue
Key takeaways
foreach (string name in names)hands you each element in order, with no index to get wrong.foreachonly reads, forward. Useforwhen you need the index, want to change elements, or go backward or in steps.- To find the highest value, start with the first element, not 0, and replace it whenever you find a bigger one.
breakends a loop at once;continueskips the rest of this iteration and goes on to the next.
Most of the time you loop through an array, you want every element, in order, and the index is just a way to get there. A foreach loop skips the index and hands you each element directly.
The shape
string[] names = { "Alice", "Bob", "Charlie" };
// read it as: for each name in names
foreach (string name in names)
{
Console.WriteLine(name);
}
Alice
Bob
Charlie
Each iteration, name holds the next element. There's no counter to start, check or step, so there's no way to get the bounds wrong.
You can write var instead of the type, and C# works it out from the array: foreach (var name in names).
Adding up with foreach
The total pattern from the for loop lesson is shorter with foreach:
decimal[] prices = { 12.75m, 10.25m, 8.44m, 9.20m };
decimal total = 0;
foreach (decimal price in prices)
{
total += price;
}
Console.WriteLine("Total: quot; + total);
Total: $40.64
Finding the highest
Another everyday pattern: keep the best value so far, and replace it whenever you find a better one.
decimal[] prices = { 12.75m, 10.25m, 21.34m, 9.20m };
decimal highest = prices[0];
foreach (decimal price in prices)
{
if (price > highest)
{
highest = price;
}
}
Console.WriteLine("Highest price: quot; + highest);
Highest price: $21.34
Start with the first element, not 0: if every price were negative, 0 would be wrong.
What foreach can't do
foreach only reads, forward, one element at a time. When you need any of these, use a for loop:
- the index itself (to print
1.,2.,3., or to compare neighbors); - to change the array's elements (
nameis a copy; assigning to it is an error); - to go backward, or skip elements.
Leaving early: break and continue
Two keywords change how any loop runs:
breakends the loop at once. The program carries on after it.continueskips the rest of this iteration and goes on to the next.
string[] names = { "Ron", "Lisa", "Kent", "Michelle" };
bool found = false;
foreach (string name in names)
{
if (name == "Kent")
{
found = true;
break;
}
}
Console.WriteLine("Found Kent: " + found);
int[] numbers = { 1, 2, 3, 4, 5, 6 };
int evenTotal = 0;
foreach (int number in numbers)
{
if (number % 2 != 0)
{
continue;
}
evenTotal += number;
}
Console.WriteLine("Total of the even numbers: " + evenTotal);
Found Kent: True
Total of the even numbers: 12
Once Kent is found there's no need to look further, so break stops the search. continue skips each odd number before it's added.
for or foreach?
| You need | Use |
|---|---|
| every element, in order, just to read it | foreach |
| the index, or to change elements | for |
| to go backward or in steps | for |
| to count a set number of times, with no array | for |
Check yourself
2 questions to try on the lesson page.
So what
foreach says what you mean, "every element", with nothing to get wrong. Reach for for when the index matters, and use break and continue to stop or skip without extra conditions.