Lesson 46 +10 XP

Pattern Matching

Pattern Matching

Pattern matching lets you test whether a value matches a shape, then extract the data you need - all in one readable step.

The is expression

is tests a type and declares a variable:

object data = "hello";

if (data is string text)
{
  Console.WriteLine(text.ToUpper());   // HELLO
}

If data is a string, it's assigned to text inside the block.

Type patterns in switch

Switch statements can match types, not just exact values:

object value = 42;

switch (value)
{
  case int i when i > 10:
    Console.WriteLine("Big int: " + i);
    break;
  case string s:
    Console.WriteLine("String: " + s);
    break;
  default:
    Console.WriteLine("Something else");
    break;
}

The when clause adds a condition to a case.

Property patterns

Match on the properties of an object:

if (person is { Age: > 18, Name: "Ada" })
{
  Console.WriteLine("Adult Ada");
}

Null checks

is not null is the clean modern null check:

if (data is not null)
{
  Console.WriteLine("data exists");
}

TL;DR

  • is tests a type and declares a variable.
  • Switch can match types + use when guards.
  • Property patterns inspect an object's properties.
  • is not null is the clean null check.