Skip to content

1.17 — Pattern Matching and Switch Expressions

← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.16 Null operators · Next: 1.18 Tuples, ref, out, in

Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —


TL;DR

  • Pattern matching lets you test a value's shape and pull data out of it in one step.
  • A switch expression (=> arms) returns a value. A switch statement (case: labels) runs code. Prefer the expression.
  • is null and is not null are safer than == null, because == can be overloaded and pattern matching cannot.

The concept

Pattern matching answers "does this value look like X?" and, if so, gives you the pieces.

The old way needed three separate steps — check the type, cast it, then use it:

if (shape is Circle)
{
    var circle = (Circle)shape;      // check again, then cast
    return Math.PI * circle.Radius * circle.Radius;
}

Pattern matching does all three at once:

if (shape is Circle circle)
    return Math.PI * circle.Radius * circle.Radius;

One line. No cast. No chance of the check and the cast getting out of sync.


How it works

Type pattern

if (value is string text)
    Console.WriteLine(text.Length);      // 'text' is already a string here

The variable is only in scope where the check succeeded, so the compiler guarantees it is valid.

Constant and null patterns

if (status is 404) { }
if (name is null) { }
if (name is not null) { }

Prefer is null over == null. Here is why: == can be overloaded by a type, so x == null might run somebody's custom code that does something unexpected. is null cannot be overloaded — it always means exactly "is this reference null". In a class with a custom ==, they can genuinely disagree.

Relational and logical patterns (C# 9)

You can compare, and combine with and, or, not:

if (age is >= 18 and < 65) { }
if (statusCode is 401 or 403) { }
if (input is not null and not "") { }

Read age is >= 18 and < 65 as "age is at least 18 and under 65". Note you do not repeat the variable name — that is the point of the syntax.

Property pattern

Match on the values inside an object:

if (order is { Status: OrderStatus.Pending, Total: > 1000 })
{
    // order is not null, AND its Status is Pending, AND its Total is over 1000
}

That single line replaces a null check plus two property comparisons. Note it also handles null for you — { ... } never matches null.

You can nest and extract:

if (order is { Customer.Address.Country: "UK", Total: var total })
{
    Console.WriteLine($"UK order worth {total}");
}

var total captures the value into a new variable while matching.

Switch expressions

A switch expression produces a value. Notice => instead of case: and break:

// Old switch statement
string GetLabel(OrderStatus status)
{
    switch (status)
    {
        case OrderStatus.Pending:   return "Waiting";
        case OrderStatus.Shipped:   return "On its way";
        case OrderStatus.Delivered: return "Complete";
        default:                    throw new ArgumentOutOfRangeException();
    }
}

// Switch expression — same thing
string GetLabel(OrderStatus status) => status switch
{
    OrderStatus.Pending   => "Waiting",
    OrderStatus.Shipped   => "On its way",
    OrderStatus.Delivered => "Complete",
    _                     => throw new ArgumentOutOfRangeException(nameof(status))
};

The _ at the bottom is the discard pattern — it matches anything, so it plays the role of default.

A big advantage: the compiler checks you covered everything. If you add a new value to OrderStatus and forget to handle it, you get a warning that the switch is not exhaustive. A switch statement gives you nothing.

Switch expressions can use any pattern, and you can add a when clause for conditions that do not fit a pattern:

decimal CalculateDiscount(Customer c) => c switch
{
    { IsVip: true, YearsActive: > 5 } => 0.20m,
    { IsVip: true }                   => 0.10m,
    { OrderCount: > 100 }             => 0.05m,
    _ when DateTime.Today.DayOfWeek == DayOfWeek.Friday => 0.02m,
    _                                 => 0m
};

Order matters. Arms are checked top to bottom and the first match wins. If you put { IsVip: true } above { IsVip: true, YearsActive: > 5 }, the more specific one can never be reached — and the compiler will warn you about that too.

List patterns (C# 11)

int[] numbers = [1, 2, 3];

if (numbers is [1, 2, 3]) { }              // exactly these three
if (numbers is [1, ..]) { }                // starts with 1
if (numbers is [_, _, var last]) { }       // three items, capture the last
if (numbers is [var first, .., var final]) { }   // at least two, capture the ends

.. is the "slice" pattern, meaning "any number of items here".


Code

A realistic example — mapping exceptions to HTTP responses:

public static ProblemDetails ToProblemDetails(this Exception ex) => ex switch
{
    NotFoundException nf => new ProblemDetails
    {
        Status = 404,
        Title  = "Not found",
        Detail = nf.Message
    },

    ValidationException { Errors.Count: > 0 } ve => new ProblemDetails
    {
        Status = 400,
        Title  = "Validation failed",
        Detail = string.Join("; ", ve.Errors)
    },

    UnauthorizedAccessException => new ProblemDetails
    {
        Status = 403,
        Title  = "Forbidden"
    },

    OperationCanceledException => new ProblemDetails
    {
        Status = 499,
        Title  = "Request cancelled"
    },

    _ => new ProblemDetails
    {
        Status = 500,
        Title  = "An unexpected error occurred"
        // deliberately no Detail — never leak internals to the client
    }
};

Read it top to bottom and it is obvious what maps to what. The equivalent if / else if chain with casts would be roughly three times as long and much easier to get wrong.

This is a very common shape in real ASP.NET Core code — see 5.12.


Interview questions

Q: What is pattern matching?

It is testing whether a value has a particular shape and extracting parts of it in the same step. The simplest form is the type pattern — if (x is Circle c) checks the type and gives you a strongly-typed variable at once, replacing the old check-then-cast pair. It extends to constants, ranges, properties, tuples and lists, and it combines with and, or and not. The practical benefit is that it removes a whole class of bug where the check and the cast drift apart.

Q: What is the difference between a switch statement and a switch expression?

A switch statement is a control-flow construct — it runs code, uses case: labels, and each branch needs break or return. A switch expression produces a value, uses => arms separated by commas, and can be assigned or returned directly. The expression form is usually better: it is shorter, it cannot fall through by accident, and the compiler warns you if you have not covered every case, which means adding a new enum value gets flagged rather than silently falling through to the default.

Q: Why prefer is null over == null?

Because == can be overloaded by the type, so x == null could invoke custom code that does something unexpected — or that throws. is null cannot be overloaded; it always means "is this reference actually null". So it is both more predictable and slightly faster. The same goes for is not null over != null.

Q: What does the when clause do in a switch?

It adds a condition that cannot be expressed as a pattern. Patterns can test types, values, ranges and properties, but they cannot call methods or reference other variables. when lets you attach an arbitrary boolean condition to an arm, so you might write _ when DateTime.Today.DayOfWeek == DayOfWeek.Friday => 0.02m.


Traps ⚠️

  • Arm order matters. The first match wins, so a general pattern above a specific one makes the specific one unreachable. The compiler warns about this — do not ignore it.
  • A switch expression with no match throws at runtime. If nothing matches and there is no _ arm, you get a SwitchExpressionException. Either cover everything or add _.
  • { } never matches null. So x is { } is actually a null check in disguise, which is clever but confusing to read. Prefer x is not null.
  • == and is can disagree on a type with a custom == operator.
  • Deeply nested property patterns become unreadable fast. Two levels is usually the limit before a named method is clearer.
  • var in a pattern always matches, including null. x is var y is always true, which makes it useless as a test — it is only for capturing.


Sources