skip to content

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%

answer

  1. text order, first match
  2. a guard can still fail
  3. earlier arm covers every value
  4. discards inside the tuple pattern

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.

solid answer

~40 s

A switch expression on `(carrier, band)` matches each arm's tuple pattern element by element, with `_` accepting any element, and the result is the first arm in text order whose pattern matches and whose `when` guard is true. So specific arms go above general ones: `(Carrier.Post, WeightBand.Heavy) when kg > 20 => 40m` before `(Carrier.Post, WeightBand.Heavy) => 25m` before `(Carrier.Post, _) => 6m`. If an earlier arm without a guard already matches every value a later arm could match, the compiler rejects the later arm with error CS8510, "The pattern is unreachable". A guarded arm such as `when kg > 20` does not count as covering anything, since its condition might be false, so the unguarded arm after it stays legal and catches what the guard turned away.

code

csharp · 17 lines
csharp
Console.WriteLine(Cost(Carrier.Post, WeightBand.Heavy, 30));    // 40
Console.WriteLine(Cost(Carrier.Post, WeightBand.Heavy, 12));    // 25
Console.WriteLine(Cost(Carrier.Post, WeightBand.Light, 1));     // 6
Console.WriteLine(Cost(Carrier.Courier, WeightBand.Light, 2));  // 9
Console.WriteLine(Cost(Carrier.Courier, WeightBand.Heavy, 30)); // 15

static decimal Cost(Carrier carrier, WeightBand band, int kg) => (carrier, band) switch
{
    (Carrier.Post, WeightBand.Heavy) when kg > 20 => 40m,
    (Carrier.Post, WeightBand.Heavy) => 25m,
    (Carrier.Post, _) => 6m,
    (_, WeightBand.Light) => 9m,
    _ => 15m,
};

enum Carrier { Post, Courier }
enum WeightBand { Light, Heavy }

go deeper

for a junior

Remember that arms are tried top to bottom and the first match wins, so the discard arm goes last.

for a middle

Explain when guards, why a guard such as kg > 20 keeps a later arm reachable, and what CS8510 and CS8846 each report.

for a senior

Review tuple switches for rows a guard silently drops into a general arm, and order arms specific to general.

for a principal

Weigh whether a dense pricing table belongs in a tuple switch or in data, so that rule changes do not need a code release.

## The shipping-cost switch A shipping calculator prices a parcel from its carrier, its weight band and its exact weight. Switching on a **tuple literal** keeps the rules in one table-like expression: ```csharp static decimal Cost(Carrier carrier, WeightBand band, int kg) => (carrier, band) switch { (Carrier.Post, WeightBand.Heavy) when kg > 20 => 40m, (Carrier.Post, WeightBand.Heavy) => 25m, (Carrier.Post, _) => 6m, (_, WeightBand.Light) => 9m, _ => 15m, }; ``` Each arm's pattern is a **positional pattern** on the tuple: one sub-pattern per element. `Carrier.Post` is a constant pattern on the first element; `_` in a position is a **discard** that accepts any value there; the final `_` arm discards the whole tuple. ## Which arm wins The rule is short: the value of a switch expression is the expression of the **first arm in text order** whose pattern matches the input and whose `when` guard, if present, evaluates to `true`. | Call | Arms that match | Winner | Result | |---|---|---|---| | `Cost(Post, Heavy, 30)` | 1, 2, 3, 5 | arm 1 (guard true) | 40 | | `Cost(Post, Heavy, 12)` | 2, 3, 5 (arm 1's guard false) | arm 2 | 25 | | `Cost(Post, Light, 1)` | 3, 4, 5 | arm 3 | 6 | | `Cost(Courier, Light, 2)` | 4, 5 | arm 4 | 9 | | `Cost(Courier, Heavy, 30)` | 5 | arm 5 | 15 | C# does not look for the *most specific* arm. Order is the whole precedence rule, which is why specific arms go above general ones and the catch-all goes last. The compiler turns all the patterns into one decision graph rather than re-testing each arm from scratch, and the language allows it to reorder property reads and `Deconstruct` calls while doing so. The result is still the one text order defines; only side effects hidden in a property getter could tell the difference. ## Case guards A **case guard** is `when` followed by a `bool` expression. It runs only after the arm's pattern has matched, and it can use the method's parameters and any variables the pattern declared: - `(Carrier.Post, WeightBand.Heavy) when kg > 20` reads `kg`, which is not part of the tuple at all. - If the guard is `false`, matching continues with the **next arm**, exactly as if the pattern had failed. - Guards let one arm test something patterns cannot express, such as a comparison between two inputs. ## Unreachable arms: error CS8510 If an earlier arm already matches **every** value a later arm could match, the later arm can never be chosen, and the compiler rejects it: ```plaintext error CS8510: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match. ``` Three common ways to trigger it: 1. A general tuple arm above a specific one: `(Carrier.Post, _)` above `(Carrier.Post, WeightBand.Heavy)`. 2. A base-type arm above a derived-type arm when switching on a class hierarchy. 3. An unguarded discard arm `_ =>` placed above other arms. This is an **error**, not a warning: the build fails. The switch statement has its own diagnostic for the same mistake, CS8120. ## Why a guard keeps a later arm reachable For subsumption the compiler treats a guarded arm as covering **nothing**, because the guard might be `false` for any given input. The one exception is a guard it can evaluate to the constant `true`, such as `when true`: that arm covers its pattern like an unguarded one. A real condition is what keeps the calculator above legal: - Arm 1, `(Post, Heavy) when kg > 20`, does not subsume arm 2, `(Post, Heavy)`, even though the patterns are identical. - Arm 2 then receives every heavy Post shipment of 20 kg or less. - The reverse order is an error: put the unguarded `(Post, Heavy)` first and the guarded copy below it is unreachable, CS8510 again. The same reasoning affects exhaustiveness. If the only arm that would cover some input carries a guard such as `when kg > 20`, the compiler cannot count it, and it warns with **CS8846**, whose text adds "However, a pattern with a 'when' clause might successfully match this value." ## Reading a tuple switch in review - Check that arms run from specific to general, with `_` last. - Check every guard: what happens to the inputs it rejects? They fall to the next matching arm, which may price them in a way nobody intended. - Prefer a discard element such as `(_, WeightBand.Light)` over listing every carrier when the carrier truly does not matter. The tuple types themselves, element names and deconstruction are covered with tuples; property and relational patterns inside an arm have their own lesson.

  • If a switch expression's only arm for heavy Post shipments carries `when kg > 20`, what does the compiler say?
    It cannot count an arm guarded by a run-time condition as covering anything, so heavy Post shipments of 20 kg or less are unhandled. It warns with CS8846, which says the switch expression is not exhaustive but adds that a pattern with a `when` clause might match the value. At run time an unmatched input throws `SwitchExpressionException`.
  • Does switching on `(carrier, band)` create a `ValueTuple` every call?
    Not necessarily. When the input is a tuple literal and no arm uses the tuple as a whole, Roslyn's lowering stores the two elements in temporaries and tests them directly, skipping the tuple creation. `ValueTuple` is a struct, so even when it is built it is not a heap allocation.
  • Why does `Shipment s => 1, Parcel p => 2` fail when `Parcel` derives from `Shipment`?
    Every `Parcel` is a `Shipment`, so the first arm already matches every value the second could match, and the compiler reports CS8510 on `Parcel p`. Put derived-type arms above base-type arms.

  • Believing C# picks the most specific matching arm regardless of order
  • Thinking a when kg > 20 guard makes the same unguarded pattern below it unreachable
  • Calling CS8510 a warning that can be ignored
  • Expecting a false guard to end the switch with no result
  • Placing the discard arm first as a default