C# control flow mirrors Java: if, else, for, while, do-while, and switch. C# also adds foreach over anything implementing IEnumerable—the foundation for LINQ later.
foreach loop
int[] nums = {1, 2, 3};
foreach (int n in nums) {
Console.WriteLine(n);
}
switch expressions (preview)
string label = score switch {
>= 90 => "A",
>= 80 => "B",
_ => "C"
};
Classic switch with case/break still works; modern switch expressions return values concisely.
Important interview questions and answers
- Q: foreach requirements?
A: The collection must expose a publicGetEnumerator()or be an array—works with lists, arrays, and LINQ results. - Q: switch on strings?
A: Supported directly—unlike older C++ where string dispatch needed maps or if/else chains.
Self-check
- How does do-while differ from while?
- What does the _ arm mean in a switch expression?
Tip: foreach works on any type with GetEnumerator()—same ergonomics as enhanced for-loops in Java.
Interview prep
- switch expression vs statement?
Switch expressions return a value (
x switch { ... }); switch statements execute blocks—both support pattern matching in modern C#.- foreach requirements?
The type needs a public
GetEnumerator()returning something withMoveNextandCurrent.