Pattern matching has grown from is type checks into a small language for asking questions about data. Most tutorials demonstrate it on shapes and animals. This one uses the code you write at work: orders, HTTP results, permissions and validation. Examples use C# 14 on .NET 10.
Type patterns with a declaration
The pattern you probably already use: test the type and get a typed variable in one step.
if (result is NotFoundResult)
return NotFound();
if (exception is DbUpdateConcurrencyException concurrency)
logger.LogWarning(concurrency, "Concurrent edit on {Entity}", concurrency.Entries[0].Metadata.Name);The variable is only in scope where the match is known to be true, so you can't use it by mistake.
The is { } and is not null checks
is not null reads better than != null, and it can't be changed by an overloaded == operator. is { } x checks for null and names the value:
if (await db.Posts.FindAsync([id], ct) is not { } post)
return Results.NotFound();
// post is non-null hereThat second form, "if it isn't there, leave", keeps the happy path unindented.
Property patterns
Match on the shape of an object, including nested properties:
if (order is { Status: OrderStatus.Paid, Customer.IsVip: true })
await priority.QueueAsync(order, ct);Customer.IsVip is an extended property pattern: a shorter way to write Customer: { IsVip: true }. A property pattern also checks for null on the way, so order and order.Customer are known to be non-null when it matches.
Relational and logical patterns
Compare with <, >, <=, >= and combine with and, or, not:
static string ShippingBand(decimal weightKg) => weightKg switch
{
<= 0 => throw new ArgumentOutOfRangeException(nameof(weightKg)),
< 1 => "Small",
>= 1 and < 10 => "Medium",
>= 10 and < 30 => "Large",
_ => "Freight",
};The compiler checks the arms in order and warns about any it can never reach, which catches overlapping ranges you'd otherwise miss.
not and or also tidy up common checks:
if (status is not (OrderStatus.Paid or OrderStatus.Shipped))
return Results.Conflict("Only paid or shipped orders can be invoiced.");Switch expressions over switch statements
When each branch produces a value, a switch expression is shorter and the compiler checks that every case is handled.
IResult ToHttp(Result<Order> result) => result switch
{
{ Success: true, Value: var order } => Results.Ok(order),
{ Error: "not-found" } => Results.NotFound(),
{ Error: "conflict" } => Results.Conflict(),
_ => Results.Problem("Something went wrong."),
};If you switch over an enum and leave a value out, the compiler warns. Treat that warning as an error: it is how adding OrderStatus.Refunded six months from now tells you every place that needs updating.
Tuple patterns for decisions with two inputs
Rules that depend on two values read like a decision table:
static bool CanEdit(Role role, PostStatus status) => (role, status) switch
{
(Role.Admin, _) => true,
(Role.Editor, PostStatus.Draft or PostStatus.InReview) => true,
_ => false,
};List patterns
Match arrays and lists by their elements. .. matches any number of items:
static string Describe(string[] args) => args switch
{
[] => "No arguments",
["--help" or "-h"] => "Help",
["migrate", var target] => $"Migrate to {target}",
["import", .. var files] when files.Length > 0 => $"Import {files.Length} files",
_ => "Unknown command",
};List patterns are handy for command-line parsing, route segments and small protocol messages. For anything bigger, a real parser is clearer.
when clauses for the rest
When a pattern can't express the condition, add a when guard:
var label = post switch
{
{ Status: PostStatus.Scheduled, PublishAtUtc: var at } when at > now => $"Scheduled for {at:d MMM}",
{ Status: PostStatus.Published } => "Published",
_ => "Draft",
};Keep guards cheap. They can run for several arms before one matches.
When not to use a pattern
- Long chains on a type you own. If every caller switches on
order.Type, the behaviour probably belongs on the order. - Deeply nested property patterns. Three levels deep is a sign to name an intermediate variable.
- Business rules hidden in a switch. If product owners talk about the rule, give it a named method and a test.
Wrapping up
Five patterns cover nearly everything: is { } x for null checks, property patterns for shape, relational patterns for ranges, switch expressions for mapping, and tuples for two-input rules. Used for decisions about data, they replace pages of if statements with code that reads like the rule it implements.