---
title: "How do you switch on a type in C# with pattern matching?"
description: "Use type patterns in a C# switch statement or switch expression to branch on an object's runtime type, with when guards and a default case."
url: "https://bugsee.com/answers/dotnet/c-switch-on-type-with-pattern-matching/"
---

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

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.

```csharp
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

- [How do properties with get and set work in C#?](https://bugsee.com/answers/dotnet/c-properties-get-and-set-explained/)
