patterncsharpdotnetTip
Pattern matching: switch expression and property patterns for clean branching
Viewed 0 times
C# 8-11
switch expressionpattern matchingproperty patterntype patternlist pattern csharp
Problem
Long if/else chains or switch statements with casting become verbose and error-prone when working with polymorphic types or complex conditions. Traditional approaches require explicit type checks and casts.
Solution
Use switch expressions with type, property, and relational patterns:
// Type pattern with property constraint
public string Describe(Shape shape) => shape switch
{
Circle c when c.Radius > 10 => $"Large circle r={c.Radius}",
Circle c => $"Small circle r={c.Radius}",
Rectangle { Width: var w, Height: var h } when w == h => "Square",
Rectangle r => $"Rectangle {r.Width}x{r.Height}",
_ => "Unknown shape"
};
// List pattern (C# 11)
string Classify(int[] arr) => arr switch
{
[] => "empty",
[var x] => $"single: {x}",
[var x, var y] => $"pair: {x},{y}",
[.., > 100] => "ends with large number",
_ => "other"
};Why
The compiler verifies exhaustiveness of switch expressions and emits a warning when not all cases are handled. Pattern matching compiles to efficient IL with type checks and direct field access — no reflection.
Gotchas
- switch expression is exhaustive but compiler only warns, not errors, on incomplete patterns — add _ discard arm
- Order of arms matters: more specific patterns must come before more general ones
- Null is not matched by type patterns — add a null arm explicitly if the input can be null
Revisions (0)
No revisions yet.