Switch expressions in C#
The modern switch returns a value and matches patterns, not just constants.
var code = 404;
// a switch expression returns a value; _ is the required fallback
var message = code switch
{
200 => "ok",
301 or 302 => "redirected",
404 => "not found",
>= 500 => "server error",
_ => $"unhandled {code}",
};
Console.WriteLine(message);
// patterns also match on type
object value = 3.5;
var kind = value switch { int n => $"int {n}", double d => $"double {d}",
_ => "something else" };
Console.WriteLine(kind);
How it works
- Each arm is
pattern => value;_catches everything else. 301 or 302and>= 500match combinations and ranges.- Type patterns like
int ntest and bind in one step.
Keywords and builtins used here
doubleintobjectorswitchvaluevar
The run, in numbers
- Lines
- 18
- Characters to type
- 431
- Tokens
- 78
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 55 seconds.
Step 2 of 3 in Flow control, step 9 of 29 in Language basics.