Pattern matching

C# 9.0 .NET 5.0

Published Updated Author Jeffrey T. Fritz Reading time

Pattern matching gives C# a precise branching model for types, values, and shapes, which makes complex decisions easier to read.

Pattern matching spans several C# releases, but the C# 9.0 era made it especially expressive with relational and logical patterns.

Why it matters

Instead of stacking if/else checks, you can describe the case you care about. That is especially useful when a branch depends on type, range, or multiple conditions at once.

It produces code that is often shorter and easier to audit, especially in validation and routing logic.

Cautions

Patterns are powerful, but they can become hard to read if you cram too much logic into one expression. Keep branches focused and favor clarity over cleverness.

If the conditions are deeply procedural, a normal block may be easier to maintain.

Branching with relational and logical patterns

Modern pattern matching lets you describe ranges and combinations directly in the branch expression.

Valid since C# 9.0

string DescribeTemperature(int celsius) => celsius switch
{
    < 0 => "freezing",
    >= 0 and <= 10 => "cold",
    > 10 and < 25 => "mild",
    _ => "warm"
};

Learn more

Pattern matching (Microsoft Learn)