Tutorials / Advanced C# and .NET / Pattern matching in modern C#

Pattern matching in modern C#

14 min read csharp
Course contents (16 lessons)
  1. The type system
  2. Records, structs and value equality
  3. Interfaces and abstract classes
  4. Generics and constraints
  5. Delegates, events and lambdas
  6. Querying and matching data
  7. LINQ in depth: deferred execution, grouping and joins
  8. IEnumerable versus IQueryable
  9. Pattern matching in modern C#
  10. Async and await: how Task really works
  11. Async patterns: cancellation, timeouts and async streams
  12. Application structure
  13. Dependency injection and service lifetimes
  14. Configuration, options and logging
  15. Data and web
  16. Entity Framework Core basics: DbContext, migrations and queries
  17. Building a minimal API with ASP.NET Core
  18. Unit testing with xunit
  19. Performance and the final project
  20. Performance basics: Span of T and fewer allocations
  21. 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, 0 and "" match those exact values.
  • Type patterns: double d matches any double and gives it the name d.
  • Relational and logical patterns: int n and > 0 matches an int that is above zero. You can also use or and not. The next arm, int n, catches the remaining ints. Because order matters, the zero arm must come first.
  • Property patterns: string { Length: > 3 } s matches a string whose Length property is over 3. Order { Total: >= 10000m } does the same with an order. You can nest them: { Customer: { Country: "PK" } }.
  • The var pattern with when: 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 null arm, 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 when clauses. If a guard needs three lines, extract a method.

Try it yourself

  1. Write a method that turns a DayOfWeek into "weekday" or "weekend" with a switch expression and or patterns.
  2. Write a shipping-cost function that takes a record Parcel(double WeightKg, string Zone) and returns a price using property patterns.
  3. Write a method with a list pattern that returns the sum of the first two items, or zero if there are fewer than two.
csharp
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