How do you switch on a type in C# with pattern matching?

← .NET and C# answers

Use a type pattern in a switch: case Circle c: in a statement or Circle c => in a switch expression. The variable is already cast to that type inside the branch.

abstract record Shape;
record Circle(double Radius) : Shape;
record Rectangle(double Width, double Height) : Shape;
 
// Switch expression (C# 8+)
static double Area(Shape shape) => shape switch
{
    Circle c            => Math.PI * c.Radius * c.Radius,
    Rectangle { Width: var w, Height: var h } => w * h,
    null                => throw new ArgumentNullException(nameof(shape)),
    _                   => throw new NotSupportedException(),
};
 
// Switch statement with a guard
switch (shape)
{
    case Circle c when c.Radius == 0:
        Console.WriteLine("empty circle");
        break;
    case Circle c:
        Console.WriteLine($"circle {c.Radius}");
        break;
    default:
        break;
}

Order matters: the first matching case wins, and the compiler reports a case that an earlier one already covers. Prefer a virtual method on the type when the behavior belongs to it; use pattern matching when you cannot modify the types.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required