Pattern matching in modern C#
Course contents (16 lessons)
- The type system
- Records, structs and value equality
- Interfaces and abstract classes
- Generics and constraints
- Delegates, events and lambdas
- Querying and matching data
- LINQ in depth: deferred execution, grouping and joins
- IEnumerable versus IQueryable
- Pattern matching in modern C#
- Async and await: how Task really works
- Async patterns: cancellation, timeouts and async streams
- Application structure
- Dependency injection and service lifetimes
- Configuration, options and logging
- Data and web
- Entity Framework Core basics: DbContext, migrations and queries
- Building a minimal API with ASP.NET Core
- Unit testing with xunit
- Performance and the final project
- Performance basics: Span of T and fewer allocations
- Final project: a notes API with EF Core, DI and logging
More than a fancy switch
Pattern matching lets you test the shape of a value and pull data out of it in one step. It started with is and a type check. In current C# it covers types, properties, numbers, ranges, collections and combinations. Used well, it replaces long chains of if, casts and null checks with short, readable rules.
A tour of patterns
object?[] things =
{
42, -7, 3.5, "hello", "", null,
new Circle(2), new Rectangle(3, 4), new Rectangle(5, 5),
new Order("A1", 12000m, "Gold"), new Order("A2", 50m, "Basic"),
new[] { 1, 2, 3 }, new[] { 9 }, Array.Empty<int>()
};
foreach (object? thing in things)
{
Console.WriteLine($"{Describe(thing),-34} <- {thing?.GetType().Name ?? "null"}");
}
Console.WriteLine(Area(new Rectangle(5, 5)));
Console.WriteLine(Discount(new Order("A3", 2000m, "Gold")));
static string Describe(object? value) => value switch
{
null => "nothing",
0 => "zero",
int n and > 0 => $"positive int {n}",
int n => $"negative int {n}",
double d => $"double {d}",
"" => "empty string",
string { Length: > 3 } s => $"long string '{s}'",
string s => $"short string '{s}'",
Circle { Radius: > 1 } c => $"big circle r={c.Radius}",
Circle => "small circle",
Rectangle { Width: var w, Height: var h } when w == h => $"square {w}",
Rectangle r => $"rectangle {r.Width}x{r.Height}",
Order { Total: >= 10000m } => "large order",
Order o => $"order {o.Id}",
int[] arr => DescribeArray(arr),
_ => "something else"
};
static string DescribeArray(int[] values) => values switch
{
[] => "empty array",
[var only] => $"array of one: {only}",
[var first, .., var last] => $"array from {first} to {last}"
};
static double Area(Shape shape) => shape switch
{
Circle c => Math.PI * c.Radius * c.Radius,
Rectangle r => r.Width * r.Height,
_ => throw new ArgumentException("Unknown shape")
};
static decimal Discount(Order order) => order switch
{
{ Tier: "Gold", Total: > 1000m } => 0.15m,
{ Tier: "Gold" } => 0.10m,
{ Total: > 5000m } => 0.05m,
_ => 0m
};
abstract record Shape;
record Circle(double Radius) : Shape;
record Rectangle(double Width, double Height) : Shape;
record Order(string Id, decimal Total, string Tier);
Walking through it
The main method, Describe, is a switch expression. Arms are tested from top to bottom, and the first match wins. Let me go through the kinds of patterns it uses.
- Constant patterns:
null,0and""match those exact values. - Type patterns:
double dmatches any double and gives it the named. - Relational and logical patterns:
int n and > 0matches an int that is above zero. You can also useorandnot. The next arm,int n, catches the remaining ints. Because order matters, the zero arm must come first. - Property patterns:
string { Length: > 3 } smatches a string whoseLengthproperty is over 3.Order { Total: >= 10000m }does the same with an order. You can nest them:{ Customer: { Country: "PK" } }. - The
varpattern withwhen: the rectangle arm pulls out width and height and then uses a guard to check they are equal. - List patterns: in
DescribeArray,[]matches an empty array,[var only]exactly one item, and[var first, .., var last]two or more, with..meaning "anything in between".
The Discount method shows why I like property patterns for business rules. Each line reads like the rule in a requirements document. A gold customer with a total over 1000 gets 15 percent, any other gold customer gets 10, anybody above 5000 gets 5.
Exhaustiveness
The compiler checks that a switch expression covers all inputs. If you leave out the discard arm and some values could slip through, you get a warning, and at runtime a SwitchExpressionException. With a sealed hierarchy of types, or an enum, the compiler can tell when you have covered every case. Add a new enum value later, and the warning shows you every switch that needs updating. This is a quiet but strong advantage over a chain of if statements, which fails silently.
In Area, I throw in the fallback arm. A throw expression is allowed there and makes the intent plain: an unknown shape is a bug, not a normal case.
Common mistakes
- Wrong arm order. The compiler reports an error when an arm can never be reached, which helps. But a broad arm placed before a narrow one with a guard can still hide it.
- Missing the null case. Type patterns do not match null. Without a
nullarm, null falls to the discard. - Overusing patterns for polymorphism. If you switch on type everywhere, a virtual method on the class is often a better design.
- Complex
whenclauses. If a guard needs three lines, extract a method.
Try it yourself
- Write a method that turns a
DayOfWeekinto "weekday" or "weekend" with a switch expression andorpatterns. - Write a shipping-cost function that takes a record
Parcel(double WeightKg, string Zone)and returns a price using property patterns. - Write a method with a list pattern that returns the sum of the first two items, or zero if there are fewer than two.
object?[] things =
{
42, -7, 3.5, "hello", "", null,
new Circle(2), new Rectangle(3, 4), new Rectangle(5, 5),
new Order("A1", 12000m, "Gold"), new Order("A2", 50m, "Basic"),
new[] { 1, 2, 3 }, new[] { 9 }, Array.Empty<int>()
};
foreach (object? thing in things)
{
Console.WriteLine($"{Describe(thing),-34} <- {thing?.GetType().Name ?? "null"}");
}
Console.WriteLine(Area(new Rectangle(5, 5)));
Console.WriteLine(Discount(new Order("A3", 2000m, "Gold")));
static string Describe(object? value) => value switch
{
null => "nothing",
0 => "zero",
int n and > 0 => $"positive int {n}",
int n => $"negative int {n}",
double d => $"double {d}",
"" => "empty string",
string { Length: > 3 } s => $"long string '{s}'",
string s => $"short string '{s}'",
Circle { Radius: > 1 } c => $"big circle r={c.Radius}",
Circle => "small circle",
Rectangle { Width: var w, Height: var h } when w == h => $"square {w}",
Rectangle r => $"rectangle {r.Width}x{r.Height}",
Order { Total: >= 10000m } => "large order",
Order o => $"order {o.Id}",
int[] arr => DescribeArray(arr),
_ => "something else"
};
static string DescribeArray(int[] values) => values switch
{
[] => "empty array",
[var only] => $"array of one: {only}",
[var first, .., var last] => $"array from {first} to {last}"
};
static double Area(Shape shape) => shape switch
{
Circle c => Math.PI * c.Radius * c.Radius,
Rectangle r => r.Width * r.Height,
_ => throw new ArgumentException("Unknown shape")
};
static decimal Discount(Order order) => order switch
{
{ Tier: "Gold", Total: > 1000m } => 0.15m,
{ Tier: "Gold" } => 0.10m,
{ Total: > 5000m } => 0.05m,
_ => 0m
};
abstract record Shape;
record Circle(double Radius) : Shape;
record Rectangle(double Width, double Height) : Shape;
record Order(string Id, decimal Total, string Tier);
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account