C# Pattern Matching: Beyond Simple Switch Statements
Pattern matching in modern C# eliminates verbose type checking and casting, making control flow more expressive.
Key Insights
- Switch expressions with patterns replace chains of if/else type checks
- Property patterns let you match on object shape without destructuring
- List patterns in C# 11 enable concise array/list matching
Switch Expressions
string Describe(object obj) => obj switch
{
int n when n < 0 => "negative",
int n => $"positive: {n}",
string s => $"text: {s}",
null => "nothing",
_ => "unknown"
};
Property Patterns
decimal CalculateDiscount(Order order) => order switch
{
{ Total: > 1000, Customer.IsPremium: true } => 0.20m,
{ Total: > 500 } => 0.10m,
{ Customer.IsPremium: true } => 0.05m,
_ => 0m
};
List Patterns (C# 11)
var result = numbers switch
{
[1, 2, 3] => "exact match",
[1, .., 3] => "starts with 1, ends with 3",
[_, _, _] => "exactly three elements",
[] => "empty",
_ => "other"
};