Skip to content
AgileLogics
5 min read

Pattern Matching in Depth

Prerequisites: Concurrent collections & synchronization

C#'s switch expression (Level 1) can match on a value's type and shape, not just an exact value — directly comparable to Java's pattern-matching switch over a sealed type:

static double Area(object shape) => shape switch {
    Circle c => Math.PI * c.Radius * c.Radius,
    Rectangle r => r.Width * r.Height,
    null => throw new ArgumentNullException(nameof(shape)),
    _ => throw new ArgumentException("Unknown shape"),
};

A record pairs especially well with pattern matching, since its properties can be matched directly:

static string Describe(Person p) => p switch {
    { Age: < 13 } => "Child",
    { Age: >= 13 and < 20 } => "Teenager",
    _ => "Adult",
};