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?
answer
- input first, then the keyword
- pattern, arrow, expression, comma
- a value, not a block of statements
- the discard arm and throw expressions
basics
~20 sA 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 sYou 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 linesConsole.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
Write the arms from memory: input, switch, pattern => expression, commas, and _ last as the catch-all.
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.
In review, spot switch expressions used for side effects and catch-all arms that hide values the code should have handled explicitly.
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