skip to content

Switch Expression Arms

A switch expression maps an input through ordered arms with when guards and warns when it is not exhaustive. Interviewers ask about arm order, discards and the unmatched case.

on this pageshow

explore

questions

5

In C#, how do you write a switch expression mapping an OrderStatus enum to a label, and how does it differ from a switch statement?

level: juniorimportance: must knowfreq 75%

answer

  1. input first, then the keyword
  2. pattern, arrow, expression, comma
  3. a value, not a block of statements
  4. the discard arm and throw expressions

basics

~20 s

A switch expression is written status switch { OrderStatus.Paid => "Paid", _ => "Other" }: comma-separated pattern => expression arms, tried in text order. Unlike a switch statement it produces a value, so each arm is an expression, never a statement block.

solid answer

~40 s

You put the input before the keyword and list arms: `status switch { OrderStatus.Pending => "Waiting", OrderStatus.Paid => "Paid", _ => throw new ArgumentOutOfRangeException(nameof(status)) }`. Each arm is a pattern, an optional `when` guard, `=>` and one expression; arms are separated by commas, a trailing comma is allowed, and there is no `case`, `break` or `default`. The result is the value of the first arm, in text order, that matches. Because it is an expression it fits in an expression-bodied member, a `return` or an argument, an arm can be a `throw` expression but not a block, and the switch expression cannot stand alone as a statement (CS0201). A switch statement runs statement sections for their side effects and produces no value.

code

csharp · 14 lines
csharp
Console.WriteLine(Label(OrderStatus.Paid));

try { Console.WriteLine(Label((OrderStatus)7)); }
catch (ArgumentOutOfRangeException ex) { Console.WriteLine($"rejected {ex.ActualValue}"); }

static string Label(OrderStatus status) => status switch
{
    OrderStatus.Pending => "Waiting for payment",
    OrderStatus.Paid => "Paid, packing soon",
    OrderStatus.Shipped => "On its way",
    _ => throw new ArgumentOutOfRangeException(nameof(status), status, "Unknown order status"),
};

enum OrderStatus { Pending, Paid, Shipped }

go deeper

for a junior

Write the arms from memory: input, switch, pattern => expression, commas, and _ last as the catch-all.

for a middle

Explain that arms are tried in text order, only the winning arm's expression runs, and why a throw expression is legal in an arm.

for a senior

In review, spot switch expressions used for side effects and catch-all arms that hide values the code should have handled explicitly.

for a principal

Decide where the team's style rules prefer an expression over a statement, and whether a catch-all arm must throw rather than return a guess.

## What a switch expression is A **switch expression** (added in C# 8) chooses one value from a list of candidates by matching an **input expression** against patterns. In an order system it turns an `OrderStatus` into the label shown to a customer: ```csharp static string Label(OrderStatus status) => status switch { OrderStatus.Pending => "Waiting for payment", OrderStatus.Paid => "Paid, packing soon", OrderStatus.Shipped => "On its way", _ => throw new ArgumentOutOfRangeException(nameof(status), status, "Unknown order status"), }; ``` The whole construct is one **expression**: it has a type and a value, so it sits on the right of `=>` in an expression-bodied method, after `return`, in a variable initializer or as a method argument. ## The parts of the syntax - The **input** comes first, then the `switch` keyword. This is the reverse of a switch statement, where `switch (status)` comes first. - Inside the braces is a list of **arms**, separated by **commas**. A trailing comma after the last arm is allowed and makes adding an arm a one-line diff. - Each arm is a **pattern**, an optional **case guard** written `when condition`, the `=>` token and a single **expression**. - The constant pattern `OrderStatus.Paid` matches one enum value; the **discard pattern** `_` matches every value, including `null` for a reference-type input, so it is the catch-all arm. - There are no `case` labels, no `break` and no `default` keyword: the discard arm plays the role `default` plays in a statement. ## How an arm is chosen 1. The input is evaluated once. 2. The result is the expression of the **first arm in text order** whose pattern matches the input and whose guard, if any, is `true`. 3. Only that arm's expression is evaluated; the others are not. 4. If no arm matches, the run time throws `System.Runtime.CompilerServices.SwitchExpressionException`, and the compiler has normally warned about that possibility with CS8509 or a related warning. Because order decides the winner, a catch-all `_` belongs last. An arm that can never be reached because an earlier one already takes all its values is a compile error (CS8510), not a silent dead line. ## Arms are expressions, not statements The right-hand side of every arm must be an expression. That rules out a block in braces, a `return` or a `break` inside an arm. Two consequences matter in code review: - A **throw expression** is allowed (C# 7.0 made `throw` usable as an expression), which is how an arm rejects a value it should never see. The example above throws `ArgumentOutOfRangeException` for a value such as `(OrderStatus)7`, a number cast to the enum that has no named member. - A switch expression cannot be used **as a statement** on its own. Writing `code switch { 1 => Console.WriteLine("a"), _ => Console.WriteLine("b") };` fails with **CS0201** ("Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement"). When the job is to run side effects rather than produce a value, a switch statement or an `if` chain is the right tool. ## Switch expression vs switch statement | Aspect | Switch expression | Switch statement | |---|---|---| | Produces a value | Yes, it has a type | No | | Arm body | One expression (or a throw expression) | Any statements | | Separator | Commas between arms | `case` labels and `break` | | Catch-all | `_ =>` arm | `default:` section | | No arm matches | `SwitchExpressionException` at run time | Nothing runs | | Missing values | Warning CS8509 | No exhaustiveness warning | The last two rows explain why teams that map values prefer the expression form: when a switch statement handles no case, control simply falls past it, while a switch expression must produce a value, so the compiler warns about unhandled inputs and the run time refuses to invent a result. ## When to reach for it Use a switch expression when each branch **computes a value** from the input: a label, a price, a next state, an HTTP status code. Keep a switch statement for branches that perform several actions or need loops and early returns. The details of switch statements, `goto case` and fall-through rules belong to the lesson on branches and loops; patterns richer than constants (property, relational and list patterns) each have their own lesson.

  • Why does a line holding only `code switch { 1 => Console.WriteLine("a"), _ => Console.WriteLine("b") };` fail to compile?
    A switch expression is an expression, and C# allows only assignments, calls, increments, decrements, `await` and object creation as expression statements. The compiler reports CS0201. Use a switch statement for side effects, or assign the switch expression's value to something.
  • Does a switch expression evaluate every arm's expression?
    No. It finds the first arm in text order whose pattern matches and whose `when` guard is true, then evaluates only that arm's expression. A method call or a `throw` in any other arm does not run.

  • Writing case labels and break inside a switch expression
  • Putting a statement block in braces as an arm's body
  • Believing the discard arm can sit anywhere because C# picks the best match
  • Using a switch expression on its own line just to call methods
  • Thinking an unmatched input makes a switch expression return default
open as a page

In a C# switch expression over a (carrier, band) tuple, which arm wins when several match, and how do when guards affect error CS8510?

level: middleimportance: must knowfreq 62%

basics

~20 s

The first arm in text order whose pattern matches and whose when guard is true wins. An arm an earlier unguarded arm covers is error CS8510; a guard such as when kg > 20 keeps lower arms reachable, since it may fail.

open as a page

How does the C# compiler decide the type of a switch expression whose arms return different types, such as an int and a null?

level: middleimportance: should knowfreq 38%

basics

~20 s

A switch expression takes the best common type of its arms when one exists. Otherwise, as with an int arm and a null arm, it takes the type it is converted to; var supplies none, so the compiler reports CS8506.

open as a page

After a teammate adds OrderStatus.Cancelled, what happens to a C# switch expression that lists the other statuses with no discard arm, at compile time and at run time?

level: seniorimportance: should knowfreq 48%

basics

~20 s

The build still succeeds but warns CS8509, naming OrderStatus.Cancelled as uncovered. At run time a Cancelled order matches no arm and throws SwitchExpressionException, whose UnmatchedValue is Cancelled. A discard arm would have hidden both signals.

open as a page

Should a team price Parcel, Pallet and Letter shipments with a C# switch expression over the Shipment types or an abstract Rate method, and should CS8509 fail the build?

level: principalimportance: should knowfreq 30%

basics

~20 s

C# cannot prove a type switch over a class hierarchy exhaustive, so a new Letter class compiles and fails at run time; an abstract Rate method fails the build with CS0534. Choose by what changes more often.

open as a page