Pattern Matching
Learn C#'s pattern matching features — type patterns, property patterns, and relational patterns.
What is Pattern Matching?
Pattern matching lets you test a value against a shape or condition, and extract data from it, all in one concise expression. It has grown into one of C#'s most powerful modern features.
Type Patterns
object value = 42;
if (value is int number){ Console.WriteLine($"It's an int: {number}");}
string Describe(object obj) => obj switch{ int i => $"Integer: {i}", string s => $"String: {s}", null => "Nothing", _ => "Unknown type"};
Console.WriteLine(Describe(42));Console.WriteLine(Describe("hello"));Output
Click Run to see what this code prints.
Property Patterns
You can match against an object's property values directly, without writing separate if-checks.
record Order(string Status, decimal Total);
string Describe(Order order) => order switch{ { Status: "Cancelled" } => "This order was cancelled.", { Total: > 1000 } => "This is a high-value order.", _ => "Standard order."};
Console.WriteLine(Describe(new Order("Active", 1500)));Output
Click Run to see what this code prints.
Relational Patterns
Since C# 9, you can use comparison operators directly inside patterns.
string Grade(int score) => score switch{ >= 90 => "A", >= 70 => "B", >= 50 => "C", _ => "F"};
Console.WriteLine(Grade(85));Output
Click Run to see what this code prints.
FAQs
Very commonly with switch expressions for classification logic, and with `is` for safe type-checking before casting an object.
Summary
- `is` and switch expressions support type, property, and relational patterns.
- Property patterns let you match directly on an object's field values.
- Relational patterns (>=, <, etc.) work directly inside switch cases.