Codiqo

Learn C# · lesson 59 of 61 · about 10 minutes

Pattern Matching

Check what type or shape a value has and pull out its parts in one step.

What you'll learn

  • Test types with is and declare a variable at the same time
  • Match on types and values in a switch expression
  • Use property and relational patterns

The dragon breathes fire

The dragon roars again, BURN!, and breathes fire. The more HP it has left, the hotter the fire: 30 while it has more than 40 HP, 20 while it has more than 20, and 10 after that. A knight in the party holds back 10 of it, and a shield on the hero's arm takes half of what's left. So the battle has to ask three questions: how much HP is left, is any adventurer in the party a Knight, and is any gear the hero bought made for the arm? With Bo in the party and the Oak shield bought, that's Bo the Knight holds back 10, The Oak shield takes half and The fire burns the hero for 10. Hero HP: 90. Each question is a pattern.

Is it one of those?

if (shape is Circle c) checks whether shape is a Circle and, if it is, gives you a variable c of type Circle to use straight away.

A switch expression can match on types too, with a different result for each:
shape switch { Circle c => ..., Square s => ..., _ => ... }

Matching on types

Shape[] shapes = [new Circle(1), new Square(3), new Circle(2)];
foreach (Shape s in shapes) Console.WriteLine(Describe(s));

static string Describe(Shape s) => s switch
{
    Circle c => $"circle, radius {c.Radius}",
    Square q => $"square, side {q.Side}",
    _ => "unknown",
};

abstract record Shape;
record Circle(double Radius) : Shape;
record Square(double Side) : Shape;

Output

circle, radius 1
square, side 3
circle, radius 2

Patterns on values and properties

Patterns can look at values as well as types:
- Relational: < 0 => "freezing", >= 30 => "hot"
- Combined: >= 13 and <= 19 => "teen"
- Property: { Qty: 0 } => "sold out" checks a property's value

Relational and property patterns

Console.WriteLine(Weather(-3) + " " + Weather(18) + " " + Weather(31));
Console.WriteLine(Status(new Item("tea", 0)) + " " + Status(new Item("cake", 3)));

static string Weather(int t) => t switch
{
    < 0 => "freezing",
    >= 0 and < 20 => "mild",
    _ => "hot",
};

static string Status(Item i) => i switch
{
    { Qty: 0 } => $"{i.Name} sold out",
    { Qty: < 5 } => $"{i.Name} running low",
    _ => $"{i.Name} in stock",
};

record Item(string Name, int Qty);

Output

freezing mild hot
tea sold out cake running low

Three patterns against the fire

dragonHp switch { > 40 => 30, > 20 => 20, _ => 10 } uses relational patterns, tried from the top, so 52 HP gives 30 and exactly 40 gives 20. party.FirstOrDefault(a => a is Knight) finds the first knight, or null if there isn't one, and is Knight shieldKnight checks it and names it in one go, so the next line can print shieldKnight.Name; a null never matches a type pattern. The gear is a record, so g is { Slot: "arm" } is a property pattern that only looks at the Slot, and is Gear shield then names the piece the hero bought, so the line says The Oak shield takes half without the name being written into the code.

Tip

Arms are tried from top to bottom, and the first match wins. Put the most specific patterns first and _ last.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.