Glossary / Switch expressions

Switch expressions

A switch expression selects one result value from a set of pattern arms. It is an expression, so it can be assigned, returned, or embedded; unlike a switch statement, each arm uses => to produce a value and arms are tested in order until one matches.

Arms, patterns, and exhaustiveness

string label = status switch
{
    Status.Pending => "waiting",
    Status.Active => "running",
    Status.Closed => "done",
    _ => throw new ArgumentOutOfRangeException(nameof(status))
};

An arm may include a when guard. The compiler reports when it can determine that an arm is unreachable or a switch expression is not exhaustive, but warnings are not runtime validation. If no arm matches, evaluation throws SwitchExpressionException (or platform/version-specific equivalent behavior). Include a deliberate fallback for open or externally sourced domains.

Switch expressions are useful for mapping values to results and modeling discriminated unions. Avoid dense nested patterns or side-effectful arm expressions; factor complex logic into methods. Arm order matters when patterns overlap.

Interview questions

  1. What does a switch expression produce? A value selected by the first matching arm.
  2. How differ from switch statement? Expression form yields a value and uses expression arms; statement form executes statements.
  3. What if no arm matches? Runtime throws a switch-expression failure; compiler may warn about non-exhaustiveness.
  4. Why order arms carefully? Earlier broad patterns can make later specific patterns unreachable.
  5. When use a fallback? For open or external domains, with explicit policy for unknown values.

References