C# and .NET • Modern C# baseline
Loops and Iteration
Use foreach for collection traversal and indexed loops when position matters.
foreach expresses iteration over a sequence without manually managing an index. A for loop is appropriate when an index or step size is part of the task. Avoid modifying a collection in a way that invalidates its active enumerator; select an algorithm or build a separate result instead.
Key points
- Prefer foreach when the index is irrelevant.
- Use break and continue sparingly when a clear loop condition is possible.
Example
int[] scores = [82, 91, 76];
int total = 0;
foreach (int score in scores)
{
total += score;
}
Console.WriteLine(total);
What to expect
249
Practice exercise
Calculate an average and handle the empty collection without dividing by zero.
Key idea: Choose iteration that states whether you need values, positions, or mutation.