C# and .NET • Modern C# baseline
Branching with if, switch, and Switch Expressions
Choose control-flow constructs that make the valid states easy to see.
Use if for general conditions and switch when behavior depends on a set of alternatives. Switch expressions return a value and can make finite mappings concise. A default arm may be appropriate for unknown input, but do not hide an unexpected state when it signals a programming error.
Key points
- Pattern matching can inspect both type and value.
- Handle newly added enum or state values intentionally.
Example
string label = status switch
{
"queued" => "Waiting",
"running" => "In progress",
"done" => "Complete",
_ => "Unknown"
};
Console.WriteLine(label);
What to expect
An input status of “running” prints “In progress”.
Practice exercise
Replace the string status with an enum and decide how to handle an unrecognized value.
Key idea: Use pattern matching to make state-dependent behavior explicit.