typestar

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

  1. Each arm is pattern => value; _ catches everything else.
  2. 301 or 302 and >= 500 match combinations and ranges.
  3. Type patterns like int n test and bind in one step.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Flow control, step 9 of 29 in Language basics.

← Previous Next →

Switch expressions in other languages