skip to content

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%

answer

  1. the warning names the missing member
  2. unnamed enum values never go away
  3. what the run time throws
  4. UnmatchedValue on the exception

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.

solid answer

~40 s

An enum switch that names every member and has no discard arm already carries warning CS8524, because any integer can be cast to the enum. Once `Cancelled` is added, the compiler sees a named member with no arm and reports CS8509 in its place with the example pattern `OrderStatus.Cancelled`. It is only a warning, so the build passes unless the team made it an error. At run time the lowered code throws `System.Runtime.CompilerServices.SwitchExpressionException` (an `InvalidOperationException`) with `UnmatchedValue` set to `Cancelled` and the message "Non-exhaustive switch expression failed to match its input." A switch that ends in `_ =>` gets no warning at all: Cancelled silently takes the catch-all arm, which is the worse outcome if that arm returns a plausible value.

code

csharp · 21 lines
csharp
using System.Runtime.CompilerServices;

try
{
    Console.WriteLine(Label(OrderStatus.Cancelled));
}
catch (SwitchExpressionException ex)
{
    Console.WriteLine(ex.Message);
    Console.WriteLine(ex.UnmatchedValue);
}

// Written before Cancelled existed; it still lists only the first three members.
static string Label(OrderStatus status) => status switch
{
    OrderStatus.Pending => "Waiting for payment",
    OrderStatus.Paid => "Paid, packing soon",
    OrderStatus.Shipped => "On its way",
};

enum OrderStatus { Pending, Paid, Shipped, Cancelled }

go deeper

for a junior

Know that a switch expression with no matching arm throws at run time instead of returning a default.

for a middle

Explain CS8509 versus CS8524 and why a cast integer is a legal enum value no named arm matches.

for a senior

Trace a SwitchExpressionException from its UnmatchedValue to the missed member or the bad data, and fix the switch without hiding the next member behind a discard arm.

for a principal

Set the team rule for enum switches: discard arms or not, and which of CS8509 and CS8524 the build treats as an error.

## The change that breaks nothing at compile time An order service maps `OrderStatus` to a customer label and to a refund rule. A teammate adds `Cancelled` to the enum. Two switch expressions in the codebase react differently: - `Label` lists `Pending`, `Paid` and `Shipped`, with **no discard arm**. - `RefundRule` lists two statuses and ends with `_ => RefundRule.None`. Neither stops the build by default. What they do differ in is what the team **sees**. ## Why an enum switch is never exhaustive by naming members A C# enum is a named set of constants over an integral type, not a closed set of values. `(OrderStatus)42` is a valid `OrderStatus` that matches no named member, and it arrives easily from a database column, a deserialized payload or an arithmetic slip. So even when a switch expression lists every named member, the compiler reports: ```plaintext warning CS8524: The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value. For example, the pattern '(OrderStatus)3' is not covered. ``` Because CS8524 is a **separate** diagnostic from CS8509, a team can give the two different severities. ## What adding a member does After `Cancelled` is added, `Label` has a **named** member without an arm, and the compiler reports the general non-exhaustive warning instead, naming the gap: ```plaintext warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern 'OrderStatus.Cancelled' is not covered. ``` The example pattern is the useful part: it points at the member that needs a decision. `RefundRule`, with its discard arm, produces **no diagnostic**, because `_` handles every input. ## What happens at run time When the compiler cannot prove a switch expression exhaustive, it lowers the unmatched path into a throw. On .NET Core 3.0 and later that is `SwitchExpressionException` from `System.Runtime.CompilerServices`: 1. It derives from `InvalidOperationException`, so an existing `catch (InvalidOperationException)` catches it. 2. Its `UnmatchedValue` property holds the input, boxed to `object`; Roslyn passes the input whenever it converts implicitly to `object`. 3. Its `Message` is "Non-exhaustive switch expression failed to match its input." followed by "Unmatched value was Cancelled." on a second line when `UnmatchedValue` is not null. On .NET Framework, which lacks that type, the compiler falls back to throwing `InvalidOperationException`. ## The discard arm trade | Switch shape | Compile time after adding Cancelled | Run time for Cancelled | |---|---|---| | Named arms, no `_` | CS8509 naming `Cancelled`, in place of CS8524 | `SwitchExpressionException` | | Named arms plus `_ => throw ...` | No new diagnostic | The exception the arm throws | | Named arms plus `_ => someValue` | No new diagnostic | `someValue`, silently | The last row is the dangerous one: a refund rule of `None` for a cancelled order is a plausible-looking wrong answer that no test written before `Cancelled` existed will catch. ## Diagnosing it in production - A stack trace through `<PrivateImplementationDetails>.ThrowSwitchExpressionException(Object)` means a switch expression without a catch-all met an input it did not expect; the frame below it names the method. - `UnmatchedValue` says whether the input was a new named member (`Cancelled`) or an unnamed one (`42`), which separates a missed code change from bad data. - Search the build log for CS8509: the warning was printed on the build that shipped the bug. ## Repairing the switch - Add the arm: `OrderStatus.Cancelled => "Cancelled"`. That clears CS8509; CS8524 remains. - For unnamed values, either accept the run-time `SwitchExpressionException` or add `_ => throw new ArgumentOutOfRangeException(nameof(status), status, null)` for a clearer message, knowing that the discard arm also silences CS8509 for the **next** new member. - Teams that want the compiler to stop the next `Cancelled` keep enum switches free of discard arms and make CS8509 an error while leaving CS8524 a warning; how a project configures severities belongs to the material on compiler warnings.

  • Why does a switch expression that lists every named member of an enum still warn?
    Any value of the underlying integral type can be cast to the enum, so `(OrderStatus)42` is a legal input no named arm matches. The compiler reports CS8524, which mentions an unnamed enum value. Only a discard arm, or another pattern covering every value, silences it.
  • If the team turns CS8524 into an error, what happens to the protection CS8509 gave?
    Every enum switch then needs a catch-all arm to compile, and that arm also handles the next new named member, so CS8509 never fires for enum switches again. Teams that want the compiler to flag new members make CS8509 an error but leave CS8524 a warning or suppress it.
  • What type does a switch expression throw when it runs on .NET Framework?
    `SwitchExpressionException` is not available there, so Roslyn emits a throw of `InvalidOperationException` instead. On .NET Core 3.0 and later the subclass is used, so a handler written for `InvalidOperationException` catches either.

  • Assuming adding an enum member breaks the build at every switch expression
  • Believing listing every named enum member makes a switch expression exhaustive
  • Thinking an unmatched switch expression returns the default value of its type
  • Adding a discard arm everywhere to make the warnings go away
  • Treating CS8509 and CS8524 as the same diagnostic