Skip to content

Pattern Matching

The Course
•
35 min study

A pattern checks whether a value has a certain shape, and can pull out parts of it in the same step. Patterns make long if chains much shorter, and they make it easy for the compiler to spot a case you've forgotten.

is, with a type

is Type name tests a type and, if it matches, gives you a typed variable. No separate cast is needed.

Test and name in one step C#
object[] values = { 42, "text", 2.5 };

foreach (object value in values)
{
    if (value is int number)
    {
        Console.WriteLine(number + 1);
    }
    else if (value is string text)
    {
        Console.WriteLine(text.ToUpper());
    }
    else
    {
        Console.WriteLine("something else");
    }
}
Check your prediction
Text
43
TEXT
something else

switch expressions

A switch expression produces a value. Arms are tried in order, and _ matches everything else. Relational patterns such as < 50 compare values, and and, or and not combine patterns.

A value from cases C#
foreach (int score in new[] { -1, 40, 75, 100, 101 })
{
    Console.WriteLine(Grade(score));
}

static string Grade(int score) => score switch
{
    < 0 or > 100 => "invalid",
    < 50 => "fail",
    < 100 => "pass",
    100 => "perfect",
};
Check your prediction
Text
invalid
fail
pass
perfect
invalid

The compiler can see that these arms cover every int, so no _ is needed. Remove the 100 arm and you get warning CS8509, which names a missing case. That's a free test.

Enums: a fixed set of names

An enum declares a type whose values are named constants, such as a task's priority. enum Priority { Low, Normal, High } gives Priority.Low, Priority.Normal and Priority.High. Each is stored as an int, numbered from 0 in the order written, and ToString gives the name. Enum.GetValues<Priority>() lists them all, and Enum.TryParse reads a name from text. A switch expression is the natural way to turn each value into something else.

Names, numbers and parsing C#
Priority normal = Priority.Normal;
Console.WriteLine(normal);
Console.WriteLine((int)normal);
Console.WriteLine(string.Join(", ", Enum.GetValues<Priority>()));

foreach (string text in new[] { "high", "Urgent", "7" })
{
    if (Enum.TryParse(text, ignoreCase: true, out Priority parsed))
    {
        Console.WriteLine($"{text}: {parsed}, defined {Enum.IsDefined(parsed)}");
    }
    else
    {
        Console.WriteLine($"{text}: not a priority");
    }
}

Console.WriteLine(Label(Priority.High));
Console.WriteLine(Label((Priority)7));

static string Label(Priority priority) => priority switch
{
    Priority.Low => "whenever",
    Priority.Normal => "this week",
    Priority.High => "today",
    _ => "unknown",
};

enum Priority { Low, Normal, High }
Check your prediction
Text
Normal
1
Low, Normal, High
high: High, defined True
Urgent: not a priority
7: 7, defined False
today
unknown

Look at 7. TryParse accepts a number as well as a name, and an enum variable can hold any int, not only the declared ones: (Priority)7 compiles and runs. That's why the switch needs its _ arm, and why Enum.IsDefined exists. Whenever an enum comes from outside, typed by a user or read from a file, check it with IsDefined after parsing. The task tracker on Day 7 does exactly that for its priorities.

Property and record patterns

Braces look inside an object. A when clause adds any further condition. With records, parentheses match the constructor's values by position. Together, these let you describe cases just about as you'd say them out loud.

Matching the insides C#
var orders = new[]
{
    new Order("Ana", 0, false),
    new Order("Ben", 120, true),
    new Order("Cy", 120, false),
    new Order("Di", 30, false),
};

foreach (Order order in orders)
{
    Console.WriteLine(Shipping(order));
}

static string Shipping(Order order) => order switch
{
    { Total: 0 } => $"{order.Name}: nothing to ship",
    { Rush: true } => $"{order.Name}: courier",
    (_, >= 100, _) => $"{order.Name}: free",
    var other when other.Name.StartsWith("D") => $"{other.Name}: local",
    _ => $"{order.Name}: standard",
};

record Order(string Name, int Total, bool Rush);
Check your prediction
Text
Ana: nothing to ship
Ben: courier
Cy: free
Di: local

Lists and types together

List patterns match a sequence's shape. [] is empty, .. skips any number of items, and a variable can capture a value. A command parser is a good match, since each case reads like an example of the input. Type patterns also work in switch, which is how you'll handle a Result in today's checkpoint.

Commands by shape C#
foreach (string line in new[] { "", "quit", "say hi", "add 2 3", "add x y", "say a lot here" })
{
    Console.WriteLine(Run(line.Split(' ', StringSplitOptions.RemoveEmptyEntries)));
}

static string Run(string[] words) => words switch
{
    [] => "empty",
    ["quit"] => "bye",
    ["say", var word] => word,
    ["say", var first, ..] => $"{first} and more",
    ["add", var a, var b] when int.TryParse(a, out int x) && int.TryParse(b, out int y) => (x + y).ToString(),
    _ => "unknown",
};
Check your prediction
Text
empty
bye
hi
5
unknown
a and more

Fix it: An arm that's never reached

This switch puts its arms in a different order from the lesson's. Run it and read the error.

An arm that's never reached C#
Console.WriteLine(Grade(-5));

static string Grade(int score) => score switch
{
    < 50 => "fail",
    < 0 => "invalid",
    _ => "pass",
};
Check your prediction
Text
error CS8510
It has already been handled by a previous arm of the switch expression

Every number below 0 is also below 50, so the < 50 arm would always take it first, and < 0 could never match. The compiler turns that into an error. Fix the order so that -5 prints invalid.

Fix it

Put the narrower pattern first:

C#
Console.WriteLine(Grade(-5));

static string Grade(int score) => score switch
{
    < 0 => "invalid",
    < 50 => "fail",
    _ => "pass",
};
Text
invalid

The rule is the same as for catch clauses: the most specific case goes first. The compiler catches this for patterns it can compare, but not for when conditions, so keep them in specific-first order too.

Your turn

Exercise

Shape areas, by pattern

Declare an abstract record Shape with sealed records Circle(double Radius), Rect(double Width, double Height) and Dot(). Write Describe(Shape shape) as a single switch expression:

  • A Dot gives dot.
  • A Rect with equal sides gives square of 4 (showing the side).
  • Any other Rect gives rect 2x3.
  • A Circle with a radius of 0 gives empty circle.
  • Any other Circle gives circle with area 3.14 to two decimal places.

Print the result for Dot, Rect(4, 4), Rect(2, 3), Circle(0) and Circle(1).

When it works, it prints:

Text
dot
square of 4
rect 2x3
empty circle
circle with area 3.14
Your workspace C#
Console.WriteLine("Start here");
Hint 1: the idea

Order matters: the specific Rect and Circle cases must appear before the general ones.

Hint 2: a first step

Start with the type pattern Dot => "dot", then add Rect with when, or capture it with a variable. :F2 formats two decimal places.

Show one solution
C#
Shape[] shapes = { new Dot(), new Rect(4, 4), new Rect(2, 3), new Circle(0), new Circle(1) };

foreach (Shape shape in shapes)
{
    Console.WriteLine(Describe(shape));
}

static string Describe(Shape shape) => shape switch
{
    Dot => "dot",
    Rect(var width, var height) when width == height => $"square of {width}",
    Rect(var width, var height) => $"rect {width}x{height}",
    Circle { Radius: 0 } => "empty circle",
    Circle circle => $"circle with area {Math.PI * circle.Radius * circle.Radius:F2}",
    _ => throw new ArgumentException("unknown shape"),
};

abstract record Shape;

sealed record Circle(double Radius) : Shape;

sealed record Rect(double Width, double Height) : Shape;

sealed record Dot() : Shape;
Text
dot
square of 4
rect 2x3
empty circle
circle with area 3.14

Order matters: the square arm comes before the general rectangle arm, and Radius: 0 before any circle, so the specific cases win. A positional pattern, Rect(var width, var height), takes a record apart, and a when clause adds a condition that a pattern can't express. The _ arm throws, because a new kind of shape that nobody handled is a bug to hear about, not something to describe as blank.

The compiler can't know that nobody will add another Shape, so without the _ arm it warns that the switch isn't exhaustive (CS8509), and an unmatched value would throw at run time. The _ arm silences that by saying what should happen: it throws, since reaching it means a bug. The Advanced course shows how to close a hierarchy.

Was this article helpful?

Your response is saved on this device.