Limited Offer
60% OFF on all plans!

Pattern Matching in C#

Use is patterns, switch expressions, property patterns, positional patterns, list patterns (C# 11+), and when guards for expressive type-safe branching.

is Patterns

1. Old Way — is + Manual Cast

Before C# 7, you checked type then cast separately — verbose and error-prone.

2. Type Pattern — is Type var (C# 7+)

`is Type variable` tests and binds in one step.

3. is Pattern with Guard Condition

Combine `is` with `and` or add an `if` condition on the bound variable.

4. Null Pattern

`is null` and `is not null` replace `== null` checks — pattern-consistent.

switch Expression

1. Type Patterns in switch

Match on the runtime type inside a switch expression.

2. Guarded Patterns with when

Add `when condition` to a switch arm for fine-grained matching.

when Guards

1. when in switch Expressions

Filter switch arms with arbitrary boolean conditions.

2. when in catch Blocks

Filter exceptions conditionally without catching and rethrowing.

Property Patterns

1. Property Pattern — is { Prop: value }

Test an object's properties inside a pattern.

2. Nested Property Patterns

Match deeply nested properties in one expression.

Positional Patterns

1. Positional Pattern with Records

Match deconstructed record components directly in a pattern.

Relational & Logical Patterns

1. Relational Patterns — < > <= >=

Match on value ranges without writing full boolean expressions.

2. Logical Patterns — and, or, not

Combine patterns with `and`, `or`, `not` for compound matching.

List Patterns (C# 11+)

1. List Pattern — [first, .., last]

Match a collection by its elements using `[..]` syntax.