Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 182 ยท Operators and Control Flow

Pattern Matching Basics

Learn the basics of C# pattern matching - the is operator, type, constant, null, relational and logical patterns, property patterns, and how patterns work in switch expressions.

Most programs spend their time asking questions about values. Is this object a string? Is that number between 1 and 10? Is this reference null? Is this order shipped to Germany? You can answer all of these with if and a pile of && operators, but the code quickly becomes noisy. Pattern matching gives you a compact, readable way to describe the shape of a value and, at the same moment, to pull data out of it.

A pattern is a small test written in a special syntax. The test either succeeds or fails, and a successful test can introduce a new variable. Patterns appear after the is operator, in case labels of a switch statement and in the arms of a switch expression. C# 7 introduced the first patterns, and every version since has added more. This lesson covers the everyday ones; Pattern Matching in Depth later in the course goes further.

The is operator and the type pattern

You may already know is as a type check: x is string is true when x holds a string. In modern C# the same operator accepts any pattern on its right-hand side. The simplest pattern is a type pattern, which only tests the type.

A declaration pattern goes one step further: it tests the type and declares a variable of that type that you can use when the test succeeds.

C# Type and declaration 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.

Before pattern matching you had to write if (item is string) { var text = (string)item; ... } or use the as operator followed by a null check. The declaration pattern does the test, the cast and the variable in one expression, and the compiler guarantees that text is only usable where it is definitely assigned.

A variable declared by a pattern in an if condition is in scope for the rest of the enclosing block, not just inside the if. That is convenient for guard clauses, but it also means you cannot reuse the same name twice in one block. In the example above the names text and d differ for that reason.

Why it beats a cast

A plain cast such as (string)item throws InvalidCastException when the type is wrong. The as operator avoids the exception by returning null, but then you must remember the null check. A declaration pattern cannot be misused that way: the variable only exists in code that runs after the match succeeded.

Constant patterns and null

A constant pattern compares the input with a constant: a number, a string, a character, a bool, an enum member or null. It does the same job as ==, but it reads nicely, and for null it has an important advantage.

C# Constant patterns, including null

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.

Why prefer x is null over x == null? A type may overload the == operator, and a badly written overload can claim that a non-null object equals null. The pattern is null always checks the reference itself and cannot be fooled. For the opposite test use is not null, which also works well with nullable reference types, because the compiler understands that the variable is non-null afterwards.

Relational patterns

Since C# 9 you can compare against a constant with <, <=, > and >= inside a pattern. These are relational patterns. On their own they look like a longer way to write a comparison, but they shine when combined with the logical patterns below and inside switch expressions.

C# Relational patterns in a switch expression

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.

A switch expression tries its arms from top to bottom and returns the value of the first one that matches. Because < 0 is handled first, the arm < 15 only ever sees values that are 0 or greater, so you do not need to write the lower bound again. The final arm uses the discard pattern _, which matches anything and acts like default. If no arm matches and there is no discard, the switch expression throws a SwitchExpressionException at run time, and the compiler warns you when it cannot prove the arms cover every input.

Logical patterns: and, or, not

Three keywords combine patterns (C# 9):

  • not negates a pattern: x is not null, c is not 'a'.
  • and requires both patterns to match: n is >= 1 and <= 10.
  • or requires at least one to match: c is 'a' or 'e' or 'i' or 'o' or 'u'.

Precedence is not, then and, then or, so use parentheses when you mix them to make the intent obvious. Note that these are pattern combinators, different from the Boolean operators &&, || and !; the left-hand side of is is evaluated only once.

C# Combining 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.

Compare n is >= 0 and <= 100 with the older n >= 0 && n <= 100. The pattern version names the variable once, which avoids typos and also avoids evaluating a complex expression twice. The last two lines show that not can wrap a parenthesized group of patterns, and that a type pattern can be followed by and plus another pattern: first the type test, then a comparison on the same value.

Common mistake: forgetting that or does not repeat the operand

Beginners often write x is 1 or x is 2. That compiles and works, but it is verbose. The idiomatic form is x is 1 or 2. Be careful when mixing the keywords: and binds tighter than or, so x is 1 or 2 and 3 means "1, or (2 and 3)", and the second branch can never match. When in doubt, add parentheses.

Property patterns, a first look

A property pattern tests properties or fields of the input inside curly braces. It lets you check several facts about an object without naming it repeatedly.

C# 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.

Each property inside the braces holds a nested pattern, so you can use constants, relational patterns and or freely. A property pattern also performs an implicit null check: missing is { IsPaid: true } is simply false for a null input, with no NullReferenceException. An empty property pattern { } matches any non-null value, and you will often see is { } x as a way to say "not null, and give me a non-nullable variable".

You can reach into nested objects with the extended syntax { Address.City: "Paris" } (C# 10). The next deeper lesson covers this together with positional, var and list patterns.

Patterns in switch statements

The same patterns work in classic case labels, with when for extra conditions. Which form should you use? A switch expression when you compute a value, a switch statement when each branch performs an action.

C# A tiny shipping calculator

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 order of the arms matters: the specific cases (<= 0, then <= 2) come before the general int arm. The compiler helps by reporting an error when an arm can never match because earlier arms already cover it (for example CS8120).

When to use patterns, and when not to

Use patterns when they make a condition shorter or safer: type checks that need a variable, null checks, range checks, and branching on several properties. Prefer a plain == or if when the test is trivial and everyone reads it at a glance; if (count == 0) does not need to be if (count is 0). Do not build giant pattern expressions either. If an arm needs more than a line to read, extract a small method with a good name.

Patterns are also cheap. The compiler turns them into the same type checks and comparisons you would write by hand, and for switch expressions over constants it can generate jump tables or binary searches.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the pattern in item is string text do when item holds an integer?

    A declaration pattern only succeeds when the value really has that type. If it fails nothing is converted or thrown, and the variable is not definitely assigned, so the compiler stops you from using it.
  2. 2. Which expression is true when n is between 1 and 10 inclusive?

    and requires both relational patterns to match. With or, almost every number would match, and (1..10) is a range, not a pattern.
  3. 3. Why is x is null considered safer than x == null?

    is null checks the reference directly. A class can overload == so that it gives surprising answers, but patterns ignore that overload.
  4. 4. What happens in a switch expression when no arm matches the input and there is no discard arm?

    A switch expression must produce a value. The compiler warns about non-exhaustive arms, and at run time an unmatched input throws SwitchExpressionException.
  5. 5. What does person is { Age: >= 18 } return when person is null?

    A property pattern first checks that the input is not null. For a null input the pattern simply does not match, so the result is false.

Summary

  • A pattern describes the shape of a value; it can also declare a variable when it matches.
  • is accepts patterns: type (is int), declaration (is string s), constant (is 42, is null) and not.
  • Relational patterns (<, <=, >, >=, C# 9) and logical patterns (and, or, not) combine into compact range and set tests.
  • Property patterns ({ Total: > 500 }) test several properties at once and never throw on null input.
  • Switch expressions try arms top to bottom; put specific arms first and finish with _ when the input space is open.
  • Prefer patterns where they improve clarity; a simple == is fine for trivial tests.

Next: Strings