C# provides standard control-flow constructs — conditionals (if, ), loops (, , ), and branching (, , ) — plus modern enhancements like switch expressions and pattern matching that make code more concise.
switchforforeachwhilebreakcontinuereturnif (score >= 90)
grade = "A";
else if (score >= 80)
grade = "B";
else
grade = "F";
// ternary and null-coalescing
string status = age >= 18 ? "adult" : "minor";
string name = input ?? "default"; // ?? — use default if input is null
name ??= "fallback"; // ??= assign if null
// traditional switch
switch (day)
{
case "Sat":
case "Sun":
type = "weekend";
break; // break required (no fall-through)
default:
type = "weekday";
break;
}
// switch EXPRESSION (C# 8) — concise, returns a value, with pattern matching
string type = day switch
{
"Sat" or "Sun" => "weekend",
_ => "weekday", // _ = default
};
// pattern matching in switch
string describe = obj switch
{
int n when n > 0 => "positive int",
string s => $"string of length {s.Length}",
null => "null",
_ => "other",
};
The modern switch expression is concise (returns a value, no break), and supports powerful pattern matching (matching types, conditions, and more) — a major improvement over the verbose traditional switch.
for (int i = 0; i < 10; i++) { }
foreach (var item in collection) { } // iterate any IEnumerable
while (condition) { }
do { } while (condition); // runs at least once
foreach (iterating any IEnumerable) is the idiomatic loop for collections.
foreach (var item in items)
{
if (item.Skip) continue; // next iteration
if (item.Stop) break; // exit loop
}
return result; // exit method
Control flow is the basic mechanism for expressing logic in every program, so understanding C#'s constructs is fundamental everyday knowledge.
While the basics are standard, modern C# enhancements are worth knowing and using: the switch expression (C# 8+) is a significant improvement over the traditional switch — concise, value-returning, no fall-through bugs (no forgotten break), and supporting pattern matching (matching on types, conditions, values, and structure), which makes complex conditional logic far cleaner than nested if-else chains.
The null-coalescing operators (??, ??=) provide clean null handling, and foreach is the idiomatic way to iterate collections.
Knowing these constructs and preferring the modern, more expressive forms (switch expressions with pattern matching over verbose switch statements, null-coalescing for defaults) is everyday knowledge for writing clean, idiomatic C#.
The switch expression and pattern matching in particular reflect modern C#'s evolution toward more functional, concise code, making them important to understand both for writing better code and for reading current C# codebases that use these features extensively.