Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 182 ยท Pattern Matching and Modern C#

Pattern Matching in Depth

Master advanced C# pattern matching - nested property patterns, positional patterns, var and discard patterns, switch expressions, when guards, parentheses and exhaustiveness.

Pattern Matching Basics introduced the everyday patterns: type tests, constants, relational patterns and the logical and, or and not. Those are the building blocks. This lesson shows what happens when you combine them with property patterns, positional patterns and the var pattern into expressions that describe whole shapes of data, and how switch expressions turn those shapes into compact decision tables.

Used well, pattern matching replaces long chains of if/else, casts and null checks with code that reads like a specification: "an order that is paid and shipped to Germany with a total above 500". Used badly, it becomes a thicket of braces. By the end you will know the full pattern vocabulary, the evaluation rules (order, when guards, exhaustiveness) and how to keep matching readable.

The full pattern vocabulary

Here is every pattern kind in one place, with the version that introduced it.

Pattern Example C#
Declaration o is string s 7
Constant x is 42, x is null 7
var p is var (x, y) 7
Discard _ 8 (in switch expressions)
Property o is { Length: 3 } 8
Positional p is (0, 0) 8
Type (no variable) o is string 9
Relational n is > 5 9
and, or, not n is > 0 and < 10 9
Parenthesized n is (> 0 and < 10) or 100 9
Extended property o is { Address.City: "Oslo" } 10
List and slice a is [1, .., 9] 11

The last row is the subject of List and Slice Patterns. Everything else is covered below.

Property patterns, nested and extended

A property pattern checks properties or fields in braces. Each entry is Name: pattern, and the pattern after the colon can be any other pattern, including another property pattern. That makes nesting natural, but C# 10 added the extended property pattern that writes the path with dots, which is much easier to read.

C# Nested and extended property patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that the extended pattern Address.Country: "DE" also handles Sam, whose Address is null: a property pattern on a null value simply does not match, so there is no NullReferenceException. Every level of the path is null-checked for you.

The order of the arms matters. Sam has Address: null, and no earlier arm matches him (the first arm needs a country), so the second arm catches him. If you put { Spent: < 100 } first, Sam would be labeled "small" instead. A switch expression picks the first arm that matches.

The empty pattern and null

{ } matches any non-null value. This is useful to turn a nullable into a non-nullable variable:

C#
if (GetName() is { } name)
{
    Console.WriteLine(name.Length);   // name is non-null here
}

You can also put a variable designation after the braces to capture the matched object, as in { Spent: > 100 } big, and capture individual properties too: { Name: var n, Spent: > 100 }.

Positional patterns

A positional pattern matches by position, using the object's deconstruction. Tuples, records and any type with a Deconstruct method support it. Instead of naming properties you write a parenthesized list of subpatterns.

C# Positional patterns with tuples and records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first function matches on a tuple built on the spot, (x, y). This is the standard trick for switching on two values at once. The second part uses a positional record pattern: a record automatically gets a Deconstruct method matching its constructor parameters, so Rect(var w, var h) pulls out width and height. The first arm for Rect adds a when guard because comparing two captured values cannot be expressed with a constant pattern.

For your own classes you provide the deconstruction:

C#
class Temperature
{
    public double Degrees { get; }
    public char Unit { get; }
    public Temperature(double degrees, char unit) => (Degrees, Unit) = (degrees, unit);
    public void Deconstruct(out double degrees, out char unit) => (degrees, unit) = (Degrees, Unit);
}

With that, t is (> 100, 'C') becomes legal. (See tuples and records for where Deconstruct comes from.)

The var pattern and discards

The var pattern always matches (even null) and just captures the value in a new variable. Alone it is pointless, but inside another pattern it lets you name a part of the value without testing it.

The discard _ also always matches but captures nothing. In positional and switch patterns it means "I do not care about this position or case".

A classic use of var is a temporary variable inside a larger test:

C# var pattern for temporaries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

is var (low, high) deconstructs a tuple into two new variables. Be aware that a var pattern never fails, so x is var y is always true; the real test is in the && that follows. Many developers find this trick too clever. Prefer a plain local variable unless the capture really simplifies the code.

Switch expressions in depth

A switch expression is an expression that yields a value. Its arms are pattern [when condition] => result, separated by commas. Rules worth memorizing:

  1. Arms are tested top to bottom; the first match wins.
  2. A later arm that can never match is a compile error (CS8510, "the pattern has already been handled"). The compiler tells you when you put a general arm before a specific one.
  3. A when clause adds an arbitrary Boolean condition for cases the patterns cannot express.
  4. If no arm matches, the expression throws SwitchExpressionException at run time, and the compiler warns (CS8509) when it cannot prove the switch covers every input. This is exhaustiveness checking.
C# when guards and the discard arm

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look at how the arms go from specific to general for each type: int n when n < 0 first, then int alone. If you wrote int => "odd integer" first, the compiler would flag every later int arm as unreachable.

Exhaustiveness with enums and sealed hierarchies

For an enum, the compiler knows every named member, but a variable of that enum can still hold any integer value, so it asks for a fallback arm too. For a hierarchy of types the compiler cannot know that you have listed every subclass (C# has no way to declare a hierarchy closed yet), so you normally end with a _ arm there too. The next example shows how to make the failure explicit instead of silent.

C# Exhaustive switch with an explicit failure arm

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Throwing from the discard arm is the idiom for "this cannot happen unless somebody adds an enum member and forgets this switch". When you later add Level.Critical, tests exercising it will hit the exception instead of silently falling into some default branch. Consider also enabling the analyzer that flags non-exhaustive switches on enums.

Parenthesized patterns and precedence

Since C# 9 you can wrap patterns in parentheses to control grouping. The precedence is not (highest), then and, then or (lowest), just as with !, && and ||. Parentheses make complex patterns self-explanatory, and are required when you want or to bind tighter than the and next to it.

C# Grouping with parentheses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

IsWorkingHour shows why parentheses matter: without them, >= 9 and < 12 or >= 13 and < 17 would still parse the same way (because and binds tighter), but the explicit grouping documents the intent for the reader. not (string or null) negates the whole group; not string or null would mean (not string) or null, which is a different and surprising test.

Patterns on types: the type pattern and subtype order

Matching on a base type matches every derived type too. Order your arms from the most derived to the least derived type, otherwise the later arm is unreachable (the compiler reports it).

C# Most specific type first

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Puppy derives from Dog, so it must come first or the Dog d arm would swallow it. This reads like virtual dispatch, but with an important design difference: a virtual method puts the behavior inside each class, while a switch puts it in one place outside. We return to that choice below.

Patterns versus polymorphism

Both let you run different code for different types. Which should you use?

  • Virtual methods are best when the behavior belongs to the type and new types appear often. Adding a new subclass requires no change to existing code.
  • Pattern matching is best when the operation is external (formatting, serialization, one-off analysis), the types are a fixed set you do not own, or you are working with data-only types like records. Adding a new operation requires no change to existing types, but adding a new type means finding every switch.

The functional-style design with sealed records and one function per operation is explored in Modeling with Records and Pattern Matching.

Common pitfalls

  • Unreachable arms. A broad pattern above a narrow one. The compiler warns; read the message, it names the earlier arm.
  • or without repeating the pattern. x is 1 or 2 is fine, but x is > 1 or < 5 is true for every number. Check your logic: you probably wanted and.
  • Forgetting that var always matches. if (x is var y) never filters anything.
  • Variables declared in patterns leak into the enclosing scope for if statements. Reusing a name in two if conditions in the same block gives error CS0128; use different names or separate blocks.
  • Switch on floating point. Patterns like 0.1 follow exact comparison rules. Use relational patterns with a tolerance for computed values.
  • Overusing deep nesting. If a pattern spans several lines of nested braces, give the parts names with helper methods or when clauses.

When a pattern is hard to read, split it: first decompose the value with a simple pattern, then handle the case in a separate switch or method. Clarity beats cleverness.

Performance

You do not need to hand-optimize patterns. The compiler turns a switch into efficient code: integer constants become jump tables or binary searches, and it avoids testing the same property twice where it can. A switch expression on types does roughly the same type checks as an if/else chain. The cost of pattern matching is usually dominated by what your properties do, so avoid expensive or side-effecting property getters inside patterns; the compiler may evaluate them more than once or in an order you did not expect.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does o is { Address.City: "Oslo" } do when o.Address is null?

    A property pattern requires the value to be non-null, and the extended path checks every level. A null Address simply makes the pattern fail.
  2. 2. Which pattern kind matches by position using the Deconstruct method?

    A positional pattern such as (var x, var y) uses the Deconstruct method (built in for tuples and records) to match values by position.
  3. 3. What happens if no arm of a switch expression matches the input at run time?

    Unlike a switch statement, a switch expression must produce a value. When nothing matches it throws SwitchExpressionException, and the compiler warns when it cannot prove the arms are exhaustive.
  4. 4. Why must a Puppy arm come before a Dog arm if Puppy derives from Dog?

    Arms are tested in order and a base-type pattern also matches derived instances. A more general arm placed first makes later ones unreachable, which the compiler reports as an error.
  5. 5. What is true about the var pattern?

    var in a pattern is a capture: it never fails. Use it to name parts of a value inside a larger pattern, not to filter.

Summary

  • The pattern vocabulary: declaration, constant, var, discard, property, positional, type, relational, logical (and, or, not), parenthesized, extended property and list patterns.
  • Property patterns can be nested or written with dotted paths ({ Address.City: "Oslo" }), and they never throw on null; { } means "not null".
  • Positional patterns use Deconstruct: tuples and records work out of the box, and a tuple built on the spot lets you switch on two values at once.
  • Switch expressions test arms top to bottom, support when guards, reject unreachable arms and warn about non-exhaustive input; end with a throwing _ arm for "impossible" cases.
  • Put the most specific type or pattern first; use parentheses to make and/or grouping explicit.
  • Prefer virtual methods when behavior belongs to the type, and pattern matching when the operation is external or the types are fixed data.

Next: List and Slice Patterns