Pattern Matching in C#
Using is, switch patterns, and property patterns to check shape and type, not just equality.
2 min read
Pattern matching lets you check not just what value something has, but what shape or type it has, in a single readable expression. C# has steadily grown this feature since C# 7, and it's now used constantly in idiomatic code.
The is pattern
The simplest form checks a type and, if it matches, binds a variable in one step:
object value = 42;
if (value is int number)
{
Console.WriteLine($"It's an int: {number}");
}value is int number does two things at once: it checks whether value is an int, and if so, gives you that value as a properly typed variable named number — no separate cast needed.
Pattern matching in switch expressions
Switch expressions (from the previous lesson) can match on type and shape, not just exact values:
object shape = new Circle(5);
string description = shape switch
{
Circle c when c.Radius > 10 => "Large circle",
Circle c => "Circle",
Rectangle r => $"Rectangle {r.Width}x{r.Height}",
null => "Nothing",
_ => "Unknown shape",
};Each arm matches a type (Circle c, Rectangle r), optionally refined with a when clause for extra conditions. This reads like a decision table and scales far better than a chain of if (shape is Circle) { ... } else if (shape is Rectangle) { ... }.
Property patterns
You can match directly against an object's properties without pulling them out first:
if (shape is Circle { Radius: > 10 })
{
Console.WriteLine("Big circle");
}This checks that shape is a Circle and that its Radius property is greater than 10, entirely inline. It composes with switch expressions too:
string sizeCategory = shape switch
{
Circle { Radius: > 10 } => "Large",
Circle { Radius: > 0 } => "Small",
_ => "Invalid",
};Relational and logical patterns
C# 9+ lets you use comparison operators directly as patterns, and combine them with and/or/not:
string SizeOf(int value) => value switch
{
< 0 => "Negative",
0 => "Zero",
> 0 and < 100 => "Small",
>= 100 => "Large",
};This reads almost like a math textbook's piecewise function, which is exactly the point — pattern matching exists to make code that's about shape and range read like the rules it's implementing, rather than a pile of nested conditionals.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.