Chapter 6: Pattern matching
In traditional programming, we often follow a fixed sequence when processing data: first check the type, then cast it to the type we need, and finally access its properties. This “ask-then-act” cycle often makes code unnecessarily verbose, and if you miss a step, it’s easy to introduce subtle bugs.
That is where pattern matching helps.
Think of pattern matching as shape recognition. Instead of step-by-step checks, you describe the shape you expect: “If the data is a circle, pull out the radius,” or “If the data is a string longer than 5, print it.” This style is not only more concise, but also closer to how we naturally think about data.
In this chapter, you will explore C# pattern matching features, including:
- How to use the type pattern with
isfor safe checks and casts. - How switch expressions make multi-branch logic clearer.
- How property patterns and list patterns let you inspect object state and collection structure.
- How logical patterns (
and,or,not) let you compose complex conditions naturally.
6.1 Getting to know pattern matching
Pattern matching is not a single keyword. It is a toolbox for expressing intent. Its core idea is to combine type checking and deconstruction into a single step.
Why do we need it?
Before pattern matching, handling objects of different types usually required three steps:
- Use
isto check the type. - Cast with
(Type). - Use the cast variable.
This is verbose and risky. For example, you might check for Circle in an if, but accidentally cast to Rectangle inside the block. These copy-paste mistakes are common in large projects.
See the difference
Suppose we want to print different information based on the type of a shape object. The following shows the old and new styles side by side.
Traditional style (before C# 7):
void ProcessShape(object shape)
{
// Step 1: check
if (shape is Circle)
{
// Step 2: cast
Circle c = (Circle)shape;
// Step 3: use
Console.WriteLine($"Circle, radius: {c.Radius}");
}
else if (shape is Rectangle)
{
Rectangle r = (Rectangle)shape;
Console.WriteLine(
$"Rectangle, width: {r.Width}, height: {r.Height}");
}
}This works, but it feels clunky. You have to write Circle twice and declare c separately.

With pattern matching (modern C#):
if (shape is Circle c) does three things at once: check, cast, and declare. That’s the key idea of pattern matching: declaratively describe the shape you expect, and let the compiler handle the details.
The evolution of pattern matching
Pattern matching evolved over several C# versions. Knowing the timeline helps you understand the syntax:
| Version | New features | Highlights |
|---|---|---|
| C# 7 | Type patterns, constant patterns | is got smarter, switch supports types. |
| C# 8 | Switch expressions, property patterns, tuple patterns | Switch became an expression and can inspect object state. |
| C# 9 | Relational patterns (<, >), logical patterns (and, or, not) |
Matching reads more like natural language. |
| C# 10 | Nested property simplification | { A.B: val } makes deep checks cleaner. |
| C# 11 | List patterns | You can match array contents. |
Note: C# 12 through C# 14 did not introduce new pattern-matching syntax, so this table stops at C# 11. Newer language features can still be used together with pattern matching, of course.
6.2 The is operator and the type pattern
The is operator is the first step into pattern matching. Before C# 7, it was merely a Boolean check. Today, it can check, cast, and bind a variable in one move.
Type pattern: check and declare in one step
A type pattern is simply: “If this is that type, give me the typed value.” See the following example:
obj is string s does two things:
- Check: Confirm that
objis astringat runtime. - Assign: If so, assign the cast value to a new variable
s.
The scope of s is the entire if block. This reduces repetition and makes the intent clearer.
Source code: DemoTypePattern
About null
One important detail: type patterns do not match null.
A type pattern checks the runtime type of an object. null means there is no object instance to match against that type.
This builds on the null checks in Chapter 3: a type pattern succeeds only when the object is non-null and its type matches. Inside the if (obj is string s) block, you can therefore use s without another null check.
Source code: DemoNullChecking
Nullable Reference Types (NRT)
If your project enables Nullable Reference Types (recommended), type patterns let you check and extract non-null values:
This way, the type pattern silences the nullable warning without any structural changes to your code, while making the intent clearer.
The var pattern: name a temporary result
Sometimes you do not care about the type. You just want to store the result of an expression. Use the var pattern. It always matches, even for null.
Source code: DemoVarPattern
This stores name?.ToUpperInvariant() in upper and reuses it in the condition. Note that while the var pattern itself can match null, any operation you perform before the pattern runs must still be null-safe. For example, name.ToUpper() would throw before pattern matching even begins. You could do it in two lines, but in expression-only contexts (like expression-bodied methods), the var pattern is a handy tool.
6.3 Switch statements and expressions
While is handles single checks, switch manages multi-branch logic. Starting in C# 8, C# also supports switch expressions.
Pain points of classic switch
First, look at the traditional style:
// Traditional style: a bit verbose
string GetDayType(DayOfWeek day)
{
switch (day)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
return "Weekend"; // Control cannot fall through to the next case
case DayOfWeek.Monday:
case DayOfWeek.Tuesday:
case DayOfWeek.Wednesday:
case DayOfWeek.Thursday:
case DayOfWeek.Friday:
return "Weekday";
default:
throw new ArgumentException("Undefined weekday value",
nameof(day));
}
}This code requires keywords and syntax elements like case, :, return, and break. Writing it feels somewhat tedious, and reading the code requires filtering through extra syntax details to discern how conditions map to results.
Food for thought
Rewrite the above switch statement using a switch expression, preserving the original return values and exception behavior. Test that both versions are equivalent across all seven days of the week and with an undefined enum value like
(DayOfWeek)99, and explain the conceptual difference between statements and expressions.
Switch expressions: clean mapping
A switch expression computes a value rather than executing statements. Think of it like a lookup table: given the left-hand input, return the right-hand result.
The same logic becomes:
The final _ arm preserves the original behavior of rejecting undefined values. For example, passing (DayOfWeek)99 throws an ArgumentException in both versions. When comparing refactored code against the original, always verify these exception cases in addition to expected inputs.
Key syntax points:
- Input first:
day switchnames the subject. - Arrows: Use
=>to map patterns to results. - No case: Just patterns. The
orin the example matches if either pattern matches; Section 6.5 explains it in more detail. - Discard pattern (
_): The default case.
Source code: DemoSwitchExpression

Exhaustiveness checks
An important safety mechanism of a switch expression is that the compiler checks whether its arms cover every possible case. This is known as exhaustiveness checking.
Suppose you are designing an order API and use OrderState to represent an order’s status. The library currently defines four states: pending payment, paid, shipped, and canceled:
You may want to add a Refunded state inside the library later. But you do not want another project that consumes the API to invent a Suspended state and pass it into your code, because your order-processing workflow would not know how to handle it.
The requirement sounds reasonable: let the library define subclasses without allowing external projects to extend the hierarchy arbitrarily. Before C# 15, the language had no direct way to express that design.
- With
abstract, external projects can also derive from the type, so it is too open. - With
sealed, not even the library can create subclasses, so it is too restrictive.
We need an option between the two. C# 15 adds the closed modifier to fill that gap. It restricts direct derived types to the assembly that declares the base type. The API author retains the ability to use inheritance, while the compiler can identify every possible direct subclass.
Closed hierarchies (C# 15)
Now consider how the C# 15 closed-hierarchy syntax restricts the scope of inheritance.
Continuing the example, declare OrderState as closed rather than abstract, and define all related order-state types in the same assembly:
The C# 15 closed modifier is a contextual keyword that can be applied to a class, including a record class. A type declared as closed is implicitly abstract, so it cannot also be declared abstract, sealed, or static.
What is a contextual keyword?
A contextual keyword has keyword meaning only in specific syntactic positions; elsewhere, it can still be used as an identifier. For example,
closedis a keyword in the modifier position of aclassdeclaration, butbool closed = true;uses it as a variable name. In a position where it might be parsed as a keyword, write@closedto use it as an identifier.
The difference between closed and sealed is:
sealedprevents inheritance everywhere.closedpermits inheritance, but direct derived types must be declared in the same assembly.
In other words, closed does not disable inheritance completely. It keeps inheritance inside the library. That is exactly what the order API needs: the library can continue to add states, but an external project cannot add a direct subclass of OrderState.
Let switch know there really are no other states
Once the compiler knows all direct derived types of OrderState, it can determine that the following switch expression covers the complete set:
There is no need for _ => throw new InvalidOperationException() here. If you later add a direct Refunded subclass, any switch that does not handle it is no longer exhaustive, and the compiler emits warning CS8509. If the project treats warnings as errors, the warning causes the build to fail.
Exhaustiveness checking is especially useful for state machines, workflows, and domain events. When you add a state, recompiling identifies the handling logic that also needs to change. If the warning is ignored and an unhandled Refunded value reaches the expression at run time, the switch expression throws SwitchExpressionException.
closed restricts only the first level
At this point, an external assembly can no longer derive directly from OrderState. However, that restriction does not automatically propagate down the entire inheritance tree. Because Pending is not closed, an external assembly can still add an order state indirectly:
This code compiles, and Suspended is still an OrderState. The earlier switch is also still considered exhaustive because Suspended derives from Pending and is therefore handled by the Pending arm. In other words, the compiler considering a switch exhaustive does not mean that external assemblies cannot extend the hierarchy at all.
If the design must prevent external assemblies from adding any order state, declare the four leaf nodes as sealed:
Now closed OrderState prevents an external assembly from adding a direct subtype, while sealed prevents anything from inheriting from the four concrete states. The library can still add another direct subtype, such as Refunded, in the same assembly, but external assemblies cannot add states directly or indirectly.
An unsealed subtype is not necessarily a flaw. If a subtype is intentionally an extension point for other assemblies, leave it unsealed. If only the same assembly should refine it further, declare the intermediate node as closed too. When designing a closed hierarchy, decide at each level which nodes remain extensible and which leaf nodes must be fully sealed.

Isn’t internal also limited to the same assembly?
At this point, you might think of another keyword whose boundary is also an assembly: internal. If OrderState is declared internal, doesn’t that likewise prevent external assemblies from inheriting from it?
That is true, but internal limits a type’s accessibility. To an ordinary external assembly, an internal type in another assembly is effectively “invisible”: it cannot use the type, much less inherit from it. Consequently, OrderState cannot appear as a parameter or return type in a public API:
closed, by contrast, restricts where direct inheritance can be declared, not the type’s visibility. As shown earlier, it can be combined with public in a type declaration:
External assemblies can still use OrderState in code, but they cannot derive a new subclass directly from it.
One important qualification remains: closed does not prevent an external assembly from extending the hierarchy indirectly through a subtype that is not declared sealed. That is why the previous section still declares concrete order states such as Pending as sealed.
Put simply, internal determines who can use a type, whereas closed determines where its direct subtypes can be declared. If OrderState is only for use inside the library, internal is sufficient. If it is part of a public API and the library must control the set of direct subtypes, use closed.
Pattern matching with Union Types (C# 15)
In addition to class hierarchies closed with closed, C# 15’s native union types (covered in Section 4.7 of Chapter 4: Immutable Design) also support exhaustiveness checking.
Union types have a fixed set of case types. In a switch expression, type patterns match the wrapped contents, and the compiler checks whether every case type is covered:
The example assumes non-null contents. A struct produced by a union declaration has a null Value in its default state, and payment is null tests those contents. Add a null => ... arm if that state is a valid input. Covering every case type does not eliminate all runtime null values. When nullable analysis determines that the contents may be null and the switch does not handle them, it reports CS8655.
Should you use closed or union types?
Closed hierarchies and union types both support exhaustive pattern matching, but they start from different designs.
- Consider a closed hierarchy when the types already have a natural common base and its subclasses share polymorphic behavior.
- A union type is usually more direct when the types do not need an inheritance relationship and you only want to group them into a fixed set of alternatives.
- Neither is appropriate when third-party packages should be able to keep adding subclasses. In that case, retain an open interface or base class.
The primary effect of closed is that direct subclasses can be added only in the declaring assembly. If your library already treats external inheritance as an extension point, adding closed changes what consumers are allowed to do. Do not use it merely to omit the default arm of a switch.
Source code: DemoExhaustiveTypes
When are switch statements still appropriate?
If the goal is to compute a result from an input, as in the day-of-week classification above, a switch expression usually makes the mapping easier to express. The compiler also checks whether any cases are missing.
If each branch needs to carry out a sequence of actions, such as logging, updating state, and calling a notification method, a switch statement is often more natural. When the branch logic lends itself to a named method, a switch expression can call that method instead. The key question is whether you want to compute a value or perform a series of actions, not how many lines the code occupies.
6.4 Constant patterns and relational patterns
Constant patterns and relational patterns make numeric checks more focused and easier to read.
Constant pattern
This is the classic switch case: match a value by equality. In pattern matching, you can use constants of different types in different arms, and you can also match null. But note that constant patterns do not perform cross-type numeric conversions for you; for example, 2m (a decimal literal) does not match 2 (an int literal). That is because pattern matching checks whether the input value is compatible with that constant pattern at runtime, instead of first applying numeric promotion the way arithmetic expressions do.
Example:
Notice the null arm. Building on Chapter 3, object? explicitly permits null, and one arm determines the result for a null input. Values not matching any of the other patterns fall through to _; no separate if is needed for null.
Relational pattern: intuitive ranges
Before C# 9, range checks often used when, which was verbose:
// Older style
case int i when i >= 60: /* ... */Now you can use relational operators directly: <, >, <=, >=. This is perfect for grading or categorizing values into buckets:
Tip: prefer relational patterns over when
Compare
case int i when i >= 90with>= 90. The latter focuses on the condition itself rather than the variable. That is how pattern matching reduces syntactic clutter.
With logical patterns (next section), these range checks can become even more concise.
Source code: DemoRelationalPattern
6.5 Logical patterns
C# 9 introduced and, or, and not, letting you combine patterns like English.
and, or, not
Their meanings are straightforward:
- and: Both sides must match.
- or: Either side matches.
- not: The pattern does not match.
Start with a range check:
Check for letters or digits
Each parenthesized part describes a range, and or combines them into “lowercase letter, uppercase letter, or digit.”
Check for non-null
This is the null check introduced in Chapter 3. The not combinator negates the null pattern, so it does not call an overloaded != operator.
Operator precedence
Like math, these operators have precedence:
not(highest)andor(lowest)
So a or b and c means a or (b and c). Still, use parentheses for clarity.
// With parentheses, clear intent
c is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z')Source code: DemoLogicalPattern
6.6 Property patterns
If a type pattern answers “who are you?”, a property pattern answers “what do you look like?” It lets you inspect object state directly.
Inspect object state
Property patterns use {} to describe property requirements. Start with a simple example:
This matches when person is not null and Age is at least 18. We apply the relational pattern introduced earlier directly to a property.
Nested properties
Suppose we also need to check the city in the address. When a property is itself an object, we can nest another property pattern inside it:
Both forms behave the same way. If person or Address is null, the pattern does not match; it matches only when the city satisfies the condition.
Comparing other null-checking styles
Suppose Person and Address use ordinary auto-implemented properties and the data does not change during the checks. We can use the null checks from Chapter 3 or a property pattern to test the same requirement:
// Traditional null checks
if (person is not null && person.Address is not null &&
person.Address.City == "Taipei" && person.Age >= 18)
{
Console.WriteLine("Adult living in Taipei");
}
// Null-conditional operators
if (person?.Address?.City == "Taipei" && person?.Age >= 18)
{
Console.WriteLine("Adult living in Taipei");
}
// Property pattern
if (person is { Address.City: "Taipei", Age: >= 18 })
{
Console.WriteLine("Adult living in Taipei");
}All three forms require an address, the city Taipei, and an age of at least 18. A property pattern combines the existence of the object and property conditions in one place. If all we need is to retrieve the city safely, person?.Address?.City is sufficient. If different failed conditions need different actions, separate checks may be clearer. For complex properties or state-changing getters, do not assume the three approaches have identical evaluation behavior.
The example project includes a null person, a null address, a minor, and a different city, so you can verify whether the three approaches give the same results for this data.
Match and extract values
You can also extract values while matching, using var or variable declarations:
This style of checking and extracting in one place keeps the logic concise and readable.
One thing to watch for: Name: var name only captures the property value. It does not mean name is definitely non-null. If you also want to exclude null, use a pattern that requires a type match, such as Name: string name.
Source code: DemoPropertyPattern
Note: Nested patterns are convenient, but deeply nested patterns can hurt readability (for example, A: { B: { C: { D: "Value" } } }). If the brace structure starts making the condition hard to read, consider splitting the logic or adding a helper property.
6.7 Positional patterns and tuple patterns
Sometimes data is not in properties, but in positions, like (x, y). This is where positional patterns shine.
Deconstruction: break an object apart
To use positional patterns, the type must support deconstruction. A record with a primary constructor, such as record Point(int X, int Y), gets a generated Deconstruct method automatically. For a regular class or a record without a primary constructor, you need to provide Deconstruct yourself.
Example with a point:
Here (0, 0) is a positional pattern. It matches values in order; with _, you can also focus on only one position.
Source code: DemoTuplePattern
Real-world example: a state machine
Tuple patterns are great for combining multiple state variables. For example, the next state of a door depends on the current state and the action.
Match (currentState, action) as a tuple:
DoorState NextState(DoorState current, DoorAction action) =>
(current, action) switch
{
(DoorState.Closed, DoorAction.Open) => DoorState.Open,
(DoorState.Open, DoorAction.Close) => DoorState.Closed,
(DoorState.Closed, DoorAction.Lock) => DoorState.Locked,
(DoorState.Locked, DoorAction.Unlock) => DoorState.Closed,
_ => current
};This reads like a state transition table. With traditional if-else chains or nested switch statements, the same rules often end up spread across deeper control flow.

6.8 List patterns
C# 11 introduced list patterns, which let you match arrays, List<T>, and other sequence-like types. This is especially useful for command-line arguments and other data with a fixed order.
Snapshot of a sequence
List patterns use []. You can specify what each position should be:
List patterns are often used when you care about only part of the sequence, such as the start or end. Two key tools are wildcards and slice patterns.
Note: List patterns require a length (Length or Count) and indexing, so they do not apply directly to arbitrary IEnumerable<T>. A custom type generally needs an accessible length property and indexer. A bare .., as in [1, .., 3], does not retrieve a slice and requires no slicing API. A pattern such as .. var rest that retrieves the slice does require the corresponding slicing capability.
Wildcards and slices
_: “There is an element here, I do not care what it is.”..: “Zero or more elements here.”
Common examples:
The combination of _ and .. lets you describe only the positions you care about, leaving the rest open—which is the essence of list pattern flexibility.
Nested patterns
Each element in a list pattern can itself be another pattern:
This composability makes list patterns flexible for complex data.
Example: a simple command parser
List patterns are great for parsing command-line arguments. Here is a simple command parser example:
string[] args = GetArgs();
string output = args switch
{
["help"] => "Usage: ...",
["version"] => "v1.0.0",
["copy", var src, var dest] => $"Copying {src} to {dest}...",
["delete", var file] => $"Deleting {file}...",
[] => "Please enter a command",
[var unknown, ..] => $"Error: unknown command '{unknown}'"
};This code reads intuitively. No need to write verbose checks like args.Length > 0 && args[0] == "copy". Pattern matching handles length and content in a single, expressive step. Techniques used here:
- Use
varto capture arguments (var src,var dest). - Use
..to match any number of remaining arguments. - Put specific patterns before general ones, such as
[var unknown, ..]. - Use
[]for the empty case.
Source code: DemoListPattern
Span<char> and string constant matching (C# 11)
In high-performance string processing scenarios, Span<char> or ReadOnlySpan<char> can avoid unnecessary string allocations. Starting in C# 11, these Span types can be directly pattern-matched against string constants:
Behind the scenes, the compiler automatically calls SequenceEqual to compare the contents. This lets you keep the performance benefits of Span while keeping the code clean and readable, with no need to manually write command.SequenceEqual("GET").
6.9 Case study: airline pricing
This section combines several of the patterns introduced earlier in a practical example. Suppose we calculate airline ticket prices based on cabin class and various pricing conditions.
Passenger types
We have a simple class hierarchy:
public class Passenger { public string? Name { get; set; } }
// First class
public class FirstClassPassenger : Passenger
{
public int AirMiles { get; set; }
}
// Business class
public class BusinessClassPassenger : Passenger
{
}
// Coach
public class CoachClassPassenger : Passenger
{
public double CarryOnKG { get; set; }
}Pricing rules
Rules:
- First class: Miles > 35,000 => 1500; miles > 15,000 => 1750; otherwise 2000.
- Business class: Flat 1000.
- Coach: Carry-on < 10 kg => 500; otherwise 650.
- Other: Flat 800.

Pattern matching solution
Use a switch expression to organize these rules:
decimal CalculateFare(Passenger p) => p switch
{
FirstClassPassenger { AirMiles: > 35_000 } => 1500m,
FirstClassPassenger { AirMiles: > 15_000 } => 1750m,
FirstClassPassenger => 2000m,
BusinessClassPassenger => 1000m,
CoachClassPassenger { CarryOnKG: < 10.0 } => 500m,
CoachClassPassenger => 650m,
_ => 800m
};This highlights best practices:
- Specific to general: Place stricter conditions first, like
> 35_000. Otherwise a broader case will match and block the specific one. - Type + property:
FirstClassPassenger { AirMiles: ... }checks both type and internal state. - Clear hierarchy: You can see pricing logic at a glance.
Source code: DemoAirlinePricing
The latter part of the sample project also shows a more complete version with extra rules such as discounts and surcharges. It is easier to understand that extended version after you first grasp the basic form shown here.
Summary
Pattern matching is an important capability in modern C#. It reduces repetitive type checks and casts, and lets you focus on whether data matches a particular shape.
- Use
isand type patterns to simplify casting. - Use switch expressions to organize complex branching logic.
- Use property, positional, and list patterns to inspect data structures.
- Use closed hierarchies (
closed) and union types (union) (C# 15) to help the compiler check switch expressions for exhaustiveness. If the patterns cover all possible inputs, an extra_ => throwarm is unnecessary. Remember thatclosedrestricts direct inheritance; it does not mean that the entire hierarchy cannot be extended.
At first, you might prefer traditional if-else blocks. Start small with is not null or a simple switch expression. As it becomes familiar, pattern matching becomes a natural way to express checking, classification, and extraction.
Glossary
| Term | Description |
|---|---|
| Closed hierarchy | A C# 15 feature that restricts direct derived classes to the declaring assembly to support exhaustiveness checking. |
| Contextual keyword | A word that has keyword meaning only in specific syntactic positions and can be used as an identifier elsewhere. |
| Exhaustiveness checking | Static analysis ensuring that a switch expression covers all possible inputs. |
| List pattern | Match sequence structure (C# 11+). |
| Logical pattern | Combine patterns with and, or, not. |
| Pattern matching | Syntax to test shapes and extract values. |
| Positional pattern | Match deconstructed elements (tuple or record). |
| Property pattern | Inspect object properties directly. |
| Switch expression | Switch with a return value and exhaustiveness checks. |
| Type pattern | Check whether a value matches a specified type; a declaration pattern can also bind a variable. |
| Union matching | Performing fully exhaustive pattern matching on C# 15 union types. |