C# and .NET • Modern C# baseline
Pattern Matching and Switch Expressions
Express type, property, and relational checks directly in control flow.
Pattern matching combines tests and extraction in a readable form. Property patterns can inspect structured data, while relational patterns are useful for ranges. Keep complex patterns understandable; extracting a named method is better than compressing many conditions into one expression.
Key points
- Switch expressions should account for expected alternatives.
- Patterns test values; they do not replace validation at external boundaries.
Example
static string Classify(int score) => score switch
{
< 0 or > 100 => "invalid",
>= 80 => "strong",
>= 50 => "developing",
_ => "starting"
};
Console.WriteLine(Classify(85));
What to expect
strong
Practice exercise
Add tests for -1, 0, 49, 50, 79, 80, 100, and 101.
Key idea: Patterns can make decision tables visible and easy to test at boundaries.