switch expressions

A switch that is an expression

A switch statement does something; a switch expression produces a value. The arms are separated by commas, each is a pattern and an expression, and the whole thing can stand where any value stands — in an assignment, an argument, a return.

Console.WriteLine("kinds:"); foreach (var n in new[] { 0, 1, 7, 12 }) { var kind = n switch { 0 => "zero", 1 => "one", < 10 => "few", _ => "many", }; Console.WriteLine($"{n}: {kind}"); }

dotnet run

kinds:
0: zero
1: one
7: few
12: many

The arms are tested in order and the first match wins, so 0 and 1 come before the relational arm < 10, which would otherwise take them too. _ is the discard: it matches any value and stands where a switch statement would write default.

There is no break in a switch expression, because the arms are expressions rather than statements: nothing falls into anything.

Relational and logical arms

A pattern may compare, combine with and, or and not, and carry a guard:

var status = 404; var message = status switch { >= 200 and < 300 => "ok", >= 400 and < 500 => "client error", >= 500 => "server error", _ => "unknown", }; Console.WriteLine(message);

dotnet run

client error

>= 200 and < 300 is one pattern, not two arms, and the same shape writes is >= 200 and < 300 outside a switch. A guard with when is the form for a condition that a pattern cannot express, such as a comparison with another variable: int n when n < limit => ....

A tuple pattern

A switch over a tuple matches several values at once, which is how a combination of two states is written without nested ifs:

var p = new Point(0, 5); Console.WriteLine(p switch { (0, 0) => "origin", (0, _) => "on the y axis", (_, 0) => "on the x axis", _ => "elsewhere", }); record Point(int X, int Y);

dotnet run

on the y axis

A positional pattern on a record takes its members in order, so (0, _) asks for an X of 0 and any Y. The same selection written as a property pattern is { X: 0 }, which the next lesson uses; both are patterns over the deconstructed value.

Exhaustiveness

The compiler checks that a switch expression covers every value of the type it switches over, and it warns with CS8509 when an arm is missing:

Program.cs(2,14): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '10' is not covered.

That line is what this container printed for a switch over an int with the arms 0, 1 and < 10 and no discard. It is a warning rather than an error, because a value outside the arms throws SwitchExpressionException at run time and the compiler cannot prove that no such value arrives.

An arm list that ends with _ is exhaustive, and so is one that covers every constant of an enum. A switch expression over a bool with both arms is exhaustive without a discard, which is why a bool switch is a good place to see the check.

Exercises

  1. Remove the _ arm from the first program and read CS8509. Which value does the message name?
  2. Add an arm for < 0 before the discard and print a negative number through the switch.
  3. Rewrite the status program with a guard when status < 300 instead of the combined pattern. Is the output the same?
  4. Switch over a tuple of a bool and an int and cover every combination. How many arms does a full cover need?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a switch expression produce?

    Answer

    A value from the first arm whose pattern matches

    The arms are expressions, so the whole switch is an expression and can be assigned or returned.

  2. What does the arm _ => "many" match?

    Answer

    Any value the arms above did not match

    The discard pattern matches anything, so it stands where a switch statement writes default.

  3. What does this program print? int n = 3; var kind = n switch { 0 => "zero", < 10 => "few", _ => "many", }; Console.WriteLine(kind);

    Answer

    few

    The arms are tested in order and 3 is not 0, so the relational arm matches and 3 is few.

  4. What does the pattern >= 200 and < 300 mean?

    Answer

    One pattern that needs both comparisons to be true

    and combines two relational patterns into one, and the value must satisfy both; 300 is excluded by < 300.

  5. What does this program print? var p = new Point(0, 5); Console.WriteLine(p switch { (0, 0) => "origin", (0, _) => "y axis", _ => "elsewhere", }); record Point(int X, int Y);

    Answer

    y axis

    The positional pattern reads X and Y in order, and X is 0 while Y may be anything, so the second arm matches.

  6. What does CS8509 report?

    Answer

    A switch expression that does not handle every value of its type

    The compiler lists the values no arm covers; it is a warning, because the check is about the type rather than one run.

  7. What happens at run time when no arm of a switch expression matches?

    Answer

    SwitchExpressionException

    The expression has to produce a value, so a value no arm covers throws; the compiler warned about it.

  8. Why does a switch expression have no break?

    Answer

    Its arms are expressions, so nothing can fall into the next one

    A switch statement needs break because its sections are statements that could run into each other; expressions cannot.

  9. What does this program print? bool ready = true; Console.WriteLine(ready switch { true => "go", false => "wait", });

    Answer

    go

    The two arms cover both values of a bool, so the switch is exhaustive and true selects go.

  10. Which pattern form reads two members of a record in a switch?

    Answer

    A positional pattern such as (0, _)

    The positional pattern deconstructs the value and matches the members in order.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev