C#workingdotnet

Switch expressions and patterns

An expression-bodied switch that returns a value, paired with the pattern vocabulary that makes its arms read like a truth table.

switch as an *expression* yields a value from the first matching arm; relational (> 0), logical (and/or/not), tuple, and when-guarded patterns let each arm describe a shape instead of running statements.

The switch expression

A classic switch statement runs side effects; a switch expression evaluates to a value. You write the input, the keyword switch, then a brace-delimited list of pattern => result arms separated by commas. Arms are tested top to bottom and the first match wins, so order matters. The discard _ is the catch-all, and unlike a statement there is no fall-through and no break.

string label = day switch
{
    0 => "Sunday",
    6 => "Saturday",
    _ => "weekday",
};

Because it is an expression it composes anywhere a value is expected β€” a return, an interpolation, a method argument. The compiler also warns when the arms are not exhaustive, nudging you to handle every case.

Relational and logical patterns

Inside an arm you can match on a comparison rather than a constant. Relational patterns use <, <=, >, >= against a constant: > 0, <= 100. Logical patterns combine others with and, or, and not, with not binding tightest, then and, then or. This lets a single arm read like a range β€” >= 0 and < 60 β€” or exclude a value with not null. These compose with property and constant patterns too.

Tuple patterns and when guards

Wrap several values in parentheses and switch on the tuple to branch on a combination at once β€” (true, false), ("rock", "scissors"). Each position is itself a pattern, so you can mix constants, relational tests, and _ discards per slot.

When a pattern alone cannot express the condition β€” it needs to compare two inputs, call a method, or test an arbitrary boolean β€” add a when guard: a clause that runs only after the pattern matches and must also be true for the arm to win. Keep the pattern for shape and the guard for the leftover logic.

Try it 5 examples

A switch expression returns a value

C#intro
0ms
ABF
Reference Β· output compiled offline, not runnable in-browser

Each arm is a constant pattern, so only the exact values 90 and 80 map to "A" and "B"; 55 matches nothing and falls through to the discard _, yielding "F". This shows the expression returns the result of the first matching arm with no fall-through.