switch Expressions
Concise value-returning switches.
What Is a switch Expression?
A switch expression evaluates an input against a series of patterns and returns a value. Unlike the classic switch statement, it is an expression, so it produces a result you can assign or return.
It uses the switch keyword after the value, with arms written as pattern => result. This makes branching logic compact and functional.
int code = 2;
string name = code switch
{
1 => "One",
2 => "Two",
_ => "Other"
};
System.Console.WriteLine(name);Statement vs Expression
The old switch statement uses case labels and break. The newer switch expression drops those keywords entirely.
Arms are separated by commas, the whole thing ends with a semicolon, and each arm yields a value rather than executing fall-through blocks. This removes a whole class of forgotten-break bugs.
// Statement style
switch (code) { case 1: result = "One"; break; }
// Expression style
result = code switch { 1 => "One", _ => "?" };