Control Flow: if, for, foreach, and switch Expressions
C#'s if/else, for and foreach loops, and modern switch expressions.
What you'll learn
- Write `if`/`else if`/`else` and a counting `for` loop
- Iterate a collection with `foreach`
- Use a modern switch expression to return a value based on a matched pattern
Explanation
C#'s if/else if/else looks close to many C-family languages: the condition is inside parentheses, e.g. if (x > 0) { ... }.
A counting for loop looks like for (int i = 0; i < n; i++) { ... }. To iterate over a collection's elements directly (a List<T>, an array, a dictionary's entries, or anything else enumerable) C# has a dedicated foreach loop: foreach (var item in collection) { ... } -- no manual index bookkeeping required.
C#'s traditional switch statement does fall through if a case has no break -- so each case still needs its own break (or another jump statement) to avoid running into the next one. Modern C# (8.0+) added a switch expression, a more compact form that evaluates to a value directly: string category = score switch { >= 90 => "A", >= 80 => "B", _ => "C" }; -- each arm is pattern => result, _ is the catch-all default, and there is no fallthrough concept at all in this form since it produces exactly one value.
Both for and foreach loops can be exited early with break, and continue skips to the next iteration, same as in most C-family languages.
Guided lab
Fill in the blank: a counting loop with odd/even output
Fill in the missing loop keyword, then predict the output.
using System;
____ (int i = 1; i <= 5; i++)
{
if (i % 2 == 0)
{
Console.WriteLine($"{i} even");
}
else
{
Console.WriteLine($"{i} odd");
}
}Stuck? Get a hint.
Common mistakes
- Forgetting a traditional C# `switch` statement falls through to the next case without an explicit `break` in each case.
- Reaching for a `for` loop with manual indexing when a `foreach` loop would iterate the collection more directly and safely.
- Confusing the modern switch expression's `pattern => result` arms with the older switch statement's `case pattern: ... break;` syntax -- they look similar but are different constructs.
Knowledge check
Takeaway
Use `foreach` to iterate a collection directly, remember traditional `switch` statements fall through without `break`, and reach for a switch expression when you want one matched value back, not a block of statements.
Summary
`if`/`for` look like other C-family languages; `foreach` iterates collections directly; traditional `switch` falls through without `break`, while the modern switch expression evaluates to a single matched value.
References
Your notes
Notes save automatically.
Finished this lesson?
Mark it complete to track your progress and schedule a future review.
AI tutor
The optional AI tutor isn't enabled in this deployment. All lessons, exercises, quizzes, and search work fully without it.