Pattern Matching in C#: The Patterns You'll Use Every Week

Type, property, relational, logical and list patterns with switch expressions, shown on real business code instead of shapes and animals.

R M Shahidul Islam Shahed · 3 min read

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.

csharp
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:

csharp
if (await db.Posts.FindAsync([id], ct) is not { } post)
    return Results.NotFound();

// post is non-null here

That 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:

csharp
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:

csharp
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:

csharp
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.

csharp
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:

csharp
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:

csharp
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:

csharp
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.

Keep reading

All articles →
C#

C# 14 Extension Members: Properties, Static Members and More

C# 14's extension blocks add extension properties and static extension members. Here's the syntax, real examples and when to reach for them.

3 min read
C#

C# 14 Features You'll Use Every Day

Extension members, the field keyword, null-conditional assignment and more — with before/after code.

1 min read
Performance & Optimisation

Measure Before You Optimise: BenchmarkDotNet for .NET Developers

Stopwatch timings lie. Set up BenchmarkDotNet, read its results, measure allocations and avoid the mistakes that make benchmarks meaningless.

4 min read