The Analogy: The Sorter on the Line
Watch someone who has worked a recycling line for twenty years. Objects come past on the belt and their hand moves before they could possibly have thought about it: glass left, card right, anything with a battery into the red bin, and that one goes to the supervisor because it is glass and it is full. They are not running a checklist. They recognise a shape — material, size, condition, all at once — and act on it.
Pattern matching is that hand. Instead of a ladder of if (x is Circle) { var c = (Circle)x; if (c.Radius > 10) ... }, you write the shape you are looking for and let the compiler do the testing, the casting and the binding in one move.
Every version of C# since 7.0 has widened what "a shape" can mean: a type, a constant, a property, a deconstruction, a range, a combination, a list. The payoff is code where the decision table is visible on the page instead of buried inside nested braces.
Syntax or Core Structure
using System;
abstract record Shape;
record Circle(double Radius) : Shape;
record Rect(double Width, double Height) : Shape;
class Program
{
static string Describe(object? item) => item switch
{
null => "null", // null pattern
0 => "the number zero", // constant pattern
int n when n < 0 => $"negative int {n}", // type + guard
int n => $"int {n}", // declaration pattern
double d when d > 0.5 => $"big double {d:F2}",
double d => $"small double {d:F2}",
"" => "empty string",
string { Length: > 5 } s => $"long string '{s}'", // property pattern
string s => $"string '{s}'",
int[] { Length: > 2 } a => $"int[{a.Length}] starting {a[0]}",
int[] a => $"short int[{a.Length}]",
Shape s => Area(s),
_ => $"unhandled {item.GetType().Name}" // discard: the catch-all
};
static string Area(Shape shape) => shape switch
{
Circle { Radius: <= 0 } => "circle with no size", // relational inside a property
Circle { Radius: var r } => $"circle area {Math.PI * r * r:F2}",
Rect(var w, var h) when w == h => $"square area {w * h:F2}", // positional pattern
Rect(var w, var h) => $"rect area {w * h:F2}",
_ => "unknown shape"
};
static string Beats(string a, string b) => (a, b) switch // tuple pattern
{
("rock", "scissors") or ("scissors", "paper") or ("paper", "rock") => $"{a} beats {b}",
(var x, var y) when x == y => "a draw",
_ => $"{b} beats {a}"
};
static void Main()
{
object?[] things =
{
null, 0, -7, 42, 0.75, "", "hello there", "hi",
new[] { 5, 6, 7 }, new[] { 1 },
new Circle(2), new Rect(3, 3), new Rect(2, 5), DateTime.MinValue
};
foreach (object? thing in things)
Console.WriteLine($" {Describe(thing)}");
Console.WriteLine(Beats("rock", "scissors"));
Console.WriteLine(Beats("paper", "scissors"));
Console.WriteLine(Beats("rock", "rock"));
if (things[8] is int[] { Length: >= 3 } nums) // 'is' pattern binds nums
Console.WriteLine($"sum of first three: {nums[0] + nums[1] + nums[2]}");
}
}
Output:
null
the number zero
negative int -7
int 42
big double 0.75
empty string
long string 'hello there'
string 'hi'
int[3] starting 5
short int[1]
circle area 12.57
square area 9.00
rect area 10.00
unhandled DateTime
rock beats scissors
scissors beats paper
a draw
sum of first three: 18
Not one cast appears in that code. string { Length: > 5 } s tested the type, read a property, compared it and bound the result in eleven characters — and Rect(var w, var h) pulled both dimensions out of a record without naming a single property.
Technical Depth: The Pattern Vocabulary
There are ten kinds of pattern. Learning them as a list once beats discovering them one Stack Overflow answer at a time.
| Pattern | Looks like | Matches when |
|---|---|---|
| Constant | 0, "help", true, Status.Open | the value equals the constant |
| Null | null, not null | the value is (or is not) null |
| Type / declaration | int n, Circle c, string _ | the runtime type matches; n is the cast result |
| Property | { Length: 0 }, { User.City: "Bath" } | each named member matches its sub-pattern |
| Positional | Rect(var w, var h) | Deconstruct succeeds and each part matches |
| Tuple | (1, var y) | applied to a tuple value or switch on (a, b) |
| Relational | > 500m, <= 0 | the comparison holds |
| Logical | and, or, not | combines any two patterns |
| List | [], [1, .., var last] | length and element patterns match (C# 11) |
| Var / discard | var x, _ | always — var binds, _ throws the value away |
They nest, and that is where the power is: Order { Customer: { Country: "GB" }, Lines.Count: > 0 } is one pattern made of three.
Statement versus expression
// switch statement: does something, needs break, arms are blocks
switch (code)
{
case 200: Log("ok"); break;
case 404:
case 410: Log("gone"); break;
default: Log("other"); break;
}
// switch expression: produces something, no break, no case keyword
string label = code switch
{
200 => "ok",
404 or 410 => "gone",
_ => "other"
};
The expression form is the one to reach for when every arm computes a value. It is shorter, and — critically — the compiler checks it for you.
Exhaustiveness and CS8509
A switch expression must produce a value, so the compiler warns (CS8509) when it cannot prove every input is handled. If nothing matches at run time you get UnhandledSwitchExpressionException, not a silent null:
static string Name(Status s) => s switch
{
Status.Open => "open",
Status.Shut => "shut" // CS8509 if Status has a third member
};
Two ways out. Add _ => throw new ArgumentOutOfRangeException(nameof(s)) and get a clear failure that names the culprit, or add a real default. Do not add _ => "" reflexively: silencing the warning is exactly how a new enum member ships as an empty string in production. Treat CS8509 as a to-do list.
Order matters, and the compiler polices it
Arms are tested top to bottom, first match wins. Put specific before general — Circle { Radius: <= 0 } above Circle, never below. Get it backwards and you get CS8120: the switch case has already been handled by a previous case, which is a genuinely useful error: an unreachable arm is always a bug.
Guards are for what patterns cannot say
when runs arbitrary code after the pattern matches:
Rect(var w, var h) when w == h => "square", // relates two parts to each other
int n when IsPrime(n) => "prime", // calls a method
{ Total: var t } when t > Limit => "over limit" // compares against a variable, not a constant
That last line is the common one: relational patterns only accept constants, so > Limit where Limit is a field will not compile. when t > Limit will.
Logical patterns replace the awkward comparisons
if (age is >= 13 and <= 19) ... // reads in one direction, unlike 13 <= age && age <= 19
if (c is 'a' or 'e' or 'i' or 'o' or 'u') ...
if (reply is not null and { Length: > 0 }) ...
if (value is not (null or "")) ... // parenthesised pattern
not has the highest precedence, then and, then or — parenthesise when you mean otherwise. And note x is not null also teaches the null-flow analyser something, which the next lesson leans on heavily.
List patterns and slices
int[] data = { 1, 2, 3, 4, 5 };
if (data is [var first, .., var last]) ... // 1 and 5
if (data is [_, _, var third, ..]) ... // 3
if (data is [1, 2, .. var rest]) ... // rest is [3, 4, 5]
bool empty = data is [];
The slice .. may appear at most once per pattern, and .. var rest allocates — on a Span<T> or string it slices without copying, on an array it copies. Handy for parsing, wasteful in a hot loop.
It compiles to good code
A switch expression is not a chain of ifs in disguise. The compiler lowers constant patterns over integers and strings to jump tables or hash switches, and it performs each type test once even when several arms mention the same type. Writing Circle { Radius: <= 0 } then Circle { Radius: var r } costs one isinst, not two. So prefer clarity; the generated dispatch is already better than what you would hand-write.
Pattern matching versus polymorphism
The polymorphism lesson argued for virtual methods, and this lesson is showing you a type switch. Both are right, on different axes:
| Question | Virtual method | Pattern switch |
|---|---|---|
| Adding a new type | easy — new subclass, nothing else changes | edit every switch |
| Adding a new operation | painful — touch every subclass | easy — one new method |
| Where the logic lives | spread across the hierarchy | in one readable table |
| Works on types you do not own | no | yes |
Works on int, tuples, arrays | no | yes |
Rule of thumb: behaviour that genuinely belongs to the object (Area, Draw, Save) goes virtual. Decisions that belong to the caller — how this app formats, prices or routes a value — go in a switch, close to the policy they express. Records plus switch expressions is the pairing here, which is why the two features shipped together.
The var pattern always matches
var x performs no test at all; it just names the value. That makes it useless alone and perfect with a guard, or as a way to compute once inside a pattern:
static string Bucket(Order o) => o switch
{
{ Lines.Count: 0 } => "empty",
var order when order.Total > 1000m => "large",
_ => "normal"
};
Note { Lines.Count: 0 } — an extended property pattern (C# 10) reaching two levels down. Before C# 10 that needed { Lines: { Count: 0 } }, which still works and still reads fine when nesting deepens.
Real World Example: An Authorisation Table and a Tiny Command Parser
Two jobs where the decision table is the feature. First, "may this account do this thing?" — the kind of rule set that turns into forty lines of nested if in every codebase that has not met tuple patterns. Second, dispatching a typed command from words the user typed.
using System;
record Account(string Role, bool Verified, decimal Balance);
class Program
{
static string Authorize(Account user, string action, decimal amount) =>
(user, action, amount) switch
{
({ Role: "admin" }, _, _) => "allow (admin override)",
({ Verified: false }, _, _) => "deny (account not verified)",
(_, "withdraw", <= 0m) => "deny (amount must be positive)",
({ Balance: var b }, "withdraw", var a) when a > b
=> $"deny (insufficient funds: {b:F2} < {a:F2})",
({ Role: "teller" }, "withdraw", > 500m) => "deny (over teller limit)",
(_, "withdraw", _) => "allow (withdrawal)",
(_, "deposit", > 0m) => "allow (deposit)",
(_, "close", _) => "review (needs manager)",
_ => "deny (unknown action)"
};
static string Run(string[] words) => words switch
{
[] => "usage: <command> [args]",
["help"] => "commands: help, add, list, delete",
["add", var item] => $"added '{item}'",
["add", var item, "x", var count] when int.TryParse(count, out int n)
=> $"added {n} x '{item}'",
["list", ..] => $"listing {words.Length - 1} filter(s)",
["delete", var item, "--force"] => $"force-deleted '{item}'",
[var cmd, ..] => $"unknown command '{cmd}'"
};
static void Main()
{
Account admin = new("admin", true, 0m);
Account teller = new("teller", true, 2000m);
Account client = new("client", true, 300m);
Account newbie = new("client", false, 1000m);
Console.WriteLine(Authorize(admin, "close", 0m));
Console.WriteLine(Authorize(newbie, "deposit", 50m));
Console.WriteLine(Authorize(client, "withdraw", -5m));
Console.WriteLine(Authorize(client, "withdraw", 250m));
Console.WriteLine(Authorize(client, "withdraw", 900m));
Console.WriteLine(Authorize(teller, "withdraw", 750m));
Console.WriteLine(Authorize(teller, "transfer", 10m));
string[][] inputs =
{
new string[0],
new[] { "help" },
new[] { "add", "milk" },
new[] { "add", "milk", "x", "3" },
new[] { "list", "red", "cheap" },
new[] { "delete", "milk", "--force" },
new[] { "explode" }
};
foreach (string[] words in inputs)
Console.WriteLine($" {Run(words)}");
}
}
Output:
allow (admin override)
deny (account not verified)
deny (amount must be positive)
allow (withdrawal)
deny (insufficient funds: 300.00 < 900.00)
deny (over teller limit)
deny (unknown action)
usage: <command> [args]
commands: help, add, list, delete
added 'milk'
added 3 x 'milk'
listing 2 filter(s)
force-deleted 'milk'
unknown command 'explode'
Read Authorize top to bottom and you are reading the policy document: admins bypass, unverified accounts do nothing, amounts must be positive, you cannot take out what you do not have, tellers cap at 500. A reviewer who knows no C# can check that against the spec — which is not something anyone can say about nested ifs. The order is the policy, so a comment above the method saying "arms are in priority order, do not reshuffle" is worth its line.
Run is the same trick over a string[]. Each arm states an exact command shape, the guard on the fourth arm both validates and parses the count, and the final [var cmd, ..] gives a decent error message instead of an index-out-of-range.
Common Mistakes
- Silencing CS8509 with
_ => default. The warning is telling you a real input is unhandled. Throw instead —_ => throw new ArgumentOutOfRangeException(nameof(x), x, "unhandled")— and the day someone adds an enum member you get a loud, named failure rather than a mystery zero. - Putting the general arm above the specific one.
Circle c => ...beforeCircle { Radius: <= 0 } => ...makes the second arm dead. The compiler catches this exact case withCS8120, but it cannot catch every version of it — awhenguard that happens to swallow a later arm compiles happily. - Comparing against a variable with a relational pattern.
amount is > limitdoes not compile whenlimitis a field or parameter; relational patterns take constants only. Use a guard:var a when a > limit. - Expecting
==semantics from a constant pattern on doubles.x switch { 0.1 => ... }matches by exact bit equality after conversion, so accumulated floating-point error slips past it. Use a relational band —>= 0.099 and <= 0.101— or work indecimal. - Forgetting
_does not match null in a type pattern position.object o = null; o switch { string _ => "s", _ => "other" }returns "other", fine — buto switch { { } => "something", null => "nothing" }is how you say "any non-null value": the empty property pattern{ }implicitly excludes null, which surprises people the first time. - Side effects in a
whenguard. Guards can run for arms that ultimately do not match, and the compiler may evaluate patterns in an order you did not write. A guard that increments a counter or writes a log is a bug waiting for a reorder. - Deconstructing with positional patterns on a type whose
Deconstructorder is not obvious.Point(var a, var b)silently swaps meaning if someone reorders the record's parameters. Property patterns —{ X: var a, Y: var b }— survive that refactor; prefer them past two components. - Reaching for a type switch where a virtual method belongs. If you find the same
switch (shape)in five files, every new shape means five edits. That is the signal to move the behaviour onto the type itself.
Best Practices
- Prefer the switch expression whenever every arm yields a value; keep the statement form for arms that perform actions.
- Order arms specific → general, and add a comment saying the order is load-bearing when it encodes a policy.
- End exhaustive switches over enums and sealed hierarchies with a throwing discard arm, not a default value.
- Use property patterns over positional ones once you are past two components — they are self-documenting and refactor-safe.
- Keep guards to a single cheap, side-effect-free expression. Anything longer belongs in a named
boolmethod that the guard calls. - Reach for
is not nullrather than!= null: it cannot be hijacked by a custom==operator, and it feeds the nullable analyser. - Pair patterns with records. Positional deconstruction, value equality and
withwere designed for exactly this style of code. - When one
switchgrows past about a dozen arms, ask whether it is really two decisions — often an outer switch on kind and an inner one on detail is far clearer than one flat table.
Practice Exercises
- Write
static string Grade(int score)as a single switch expression using relational and logical patterns:< 0or> 100returns"invalid",>= 70is"distinction",>= 50is"pass", anything else"fail". Prove it with the inputs-1, 0, 49, 50, 69, 70, 100, 101. - Define
record Event(string Kind, int Count)and writeSummarise(Event e)that uses property patterns and a guard to return"quiet"forCountof 0,"burst"whenKindis"click"andCountexceeds 100,"click run"for any other click, and"{Kind} x{Count}"otherwise. - Using list patterns, write
Parse(string[] args)that recognises[],["--version"],["--out", var path],[var input, "--out", var path]and a slice arm that reports how many extra arguments were supplied. Return a descriptive string for each. - Take an
if/elseladder you have written (or theAuthorizemethod above, minus itsadminarm) and rewrite it as a tuple-pattern switch expression. Then add one new rule at the top and note how many lines you had to touch compared with the ladder version.