Pattern matching
Pattern matching tests the shape of a value (its type, range, properties or list structure) and pulls its parts out into variables. Unlike an if else chain, the compiler understands patterns, so it can flag unreachable arms and missing cases.
24.1 Why is it used?
- In an if else chain the first true condition wins, and a wrong order is silently a bug.
- For the compiler, if/else branches are just separate conditions, so dead branches are never reported.
- Patterns let the compiler see all arms together: unreachable arm = CS8510, missing case = CS8509.
- Complex conditions (ranges, nested properties, array shapes) become short, readable arms.
24.2 The bug: if else order
C#
Console.WriteLine(DeliveryFee(3));Console.WriteLine(DeliveryFee(12));Console.WriteLine(DeliveryFee(25)); static int DeliveryFee(double kg){ if (kg > 5) return 80; else if (kg > 20) return 150; else return 40;}Output
$ dotnet run Fee.cs408080- 25 kg: kg > 5 is true, so it returns 80; the kg > 20 branch never runs.
- No warning from the compiler.
24.3 Relational patterns in a switch expression
- > 5 is a relational pattern: the input is compared directly with a constant.
- With the same wrong order, the build now fails with CS8510 (unreachable arm).
C#
static int DeliveryFee(double kg) => kg switch{ > 5 => 80, > 20 => 150, _ => 40};Output
$ dotnet run Fee.csFee.cs(8,5): error CS8510: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match.The build failed. Fix the build errors and run again.Fix: write the arms from the smallest weight to the largest; _ is the discard that matches everything else.
C#
static int DeliveryFee(double kg) => kg switch{ <= 5 => 40, <= 20 => 80, _ => 150};Output
$ dotnet run Fee.cs4080150- Step 1
1.Input is evaluated once
- Step 2
2.Arms are tested from top to bottom
- Step 3
3.First matching arm wins, its result is returned
- Step 4
4.No arm matches: SwitchExpressionException at run time
- Step 5
5.Compiler guards: CS8509 missing case, CS8510 unreachable arm
24.4 Logical patterns: and, or, not
C#
Console.WriteLine(Slot(9));Console.WriteLine(Slot(23));Console.WriteLine(IsOpen(20)); static string Slot(int hour) => hour switch{ < 0 or > 23 => "Invalid", >= 9 and < 12 => "Morning", >= 12 and < 18 => "Afternoon", >= 18 and < 21 => "Evening", _ => "Closed"}; static bool IsOpen(int hour) => hour is >= 9 and < 21;Output
$ dotnet run Slot.csMorningClosedTrue- >= 9 and < 12 is a clean range without repeating hour.
- The same patterns work with is inside an if.
24.5 Type + property patterns
- Card { Amount: > 50000 }: the value is a Card and its Amount is above 50,000.
- Card { Network: "RuPay" }: property pattern on a string constant.
- Card c: type pattern that also declares a variable c for other cards.
- null => ... handles a null payment explicitly.
C#
static decimal Fee(Payment? p) => p switch{ Card { Amount: > 50000 } => 1000, Card { Network: "RuPay" } => 0, Card c => c.Amount * 0.02m, Upi => 0, null => throw new ArgumentNullException(), _ => throw new NotSupportedException()}; abstract record Payment(decimal Amount);record Card(decimal Amount, string Network) : Payment(Amount);record Upi(decimal Amount, string Vpa) : Payment(Amount);Output
$ dotnet run Payments.csCard: 1000Card: 0Card: 24.00Upi: 0Extended property pattern: Customer.IsPrime looks inside a nested object.
C#
static decimal Discount(Order o) => o switch{ { Total: >= 5000, Customer.IsPrime: true } => 500, { Total: >= 5000 } => 200, { Coupon: "FIRST50" } => 50, _ => 0}; record Customer(string Name, bool IsPrime);record Order(Customer Customer, decimal Total, string? Coupon);Output
$ dotnet run Discount.cs50020050024.6 List patterns: the shape of an array
C#
Console.WriteLine(Run(["add", "Tea", "2"]));Console.WriteLine(Run(["remove", "Tea"]));Console.WriteLine(Run(["clear", "--force"]));Console.WriteLine(Run([]));Console.WriteLine(Run(["add", "Tea"])); static string Run(string[] cmd) => cmd switch{ [] => "No command", ["add", var item, var qty] => $"Added {qty} x {item}", ["remove", var item] => $"Removed {item}", ["clear", ..] => "Cart cleared", _ => "Unknown command"};Output
$ dotnet run Cart.csAdded 2 x TeaRemoved TeaCart clearedNo commandUnknown command- [] matches an empty array; ["add", var item, var qty] needs exactly three elements.
- .. (slice) matches zero or more elements; _ matches exactly one.
- ["add", "Tea"] has no quantity, so it falls to Unknown command.
C#
int[] codes = [1, 3];Console.WriteLine(codes is [1, .., 3]);Console.WriteLine(codes is [1, _, 3]);Output
$ dotnet run Checkpoint.csTrueFalse24.7 Pattern types at a glance
| Pattern | Example | Matches when |
|---|---|---|
| Relational | <= 20 | Input compares true with the constant |
| Logical | >= 9 and < 12, not null | Combined patterns are true |
| Type | Card c | Input is of that type (variable declared) |
| Property | { Network: "RuPay" } | Properties match their sub-patterns |
| Extended property | { Customer.IsPrime: true } | A nested property matches |
| List | ["add", var item, var qty], [1, .., 3] | Array/list has that shape |
| Discard | _ | Anything (default arm) |
24.8 Common mistakes
- not with or without brackets: status is not "Paid" or "Refunded" applies not only to Paid, so Refunded returns True (warning CS9336: pattern is redundant).
- Fix: status is not ("Paid" or "Refunded"); now Paid and Refunded both give False.
- General arms above specific ones (CS8510).
- Ignoring CS8509 (missing case), which becomes a SwitchExpressionException at run time.
- Myth: pattern matching is slow like reflection. The compiler turns it into normal type checks and comparisons (an optimized decision tree).
C#
static bool CanCancel(string status) => status is not ("Paid" or "Refunded"); // Pending: True, Paid: False// Refunded: False24.9 Rules
- To pick a result from one value, use a switch expression instead of an if else chain.
- Specific arms first, general arms last.
- Use is null / is not null for null checks.
- Put brackets around (A or B) after not.
- Never ignore CS8509 or CS9336.
24.10 Interview tips
- Pattern matching tests the shape of a value and extracts its parts into variables.
- Kinds: type, relational, logical (and/or/not), property (including nested), list patterns with .. slice.
- Works with both is and the switch expression.
- The compiler reports missing cases (CS8509) and unreachable arms (CS8510), so fewer ordering bugs than if/else.