skip to content

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%

answer

  1. class hierarchies are never closed
  2. CS0534 vs a run-time throw
  3. new types or new operations
  4. enums differ from type switches

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.

solid answer

~40 s

With an abstract `Shipment`, adding `sealed class Letter : Shipment` without overriding an abstract `Rate()` is error CS0534, so the compiler finds every gap. A switch expression over `Parcel p` and `Pallet p` warns CS8509 with pattern `_` from the start, because the compiler treats a class hierarchy as open to new subclasses; it must end in a discard arm, and `Letter` then compiles and fails or misprices at run time. So virtual dispatch fits when new shipment types are the common change; switch expressions fit when new operations are, or when the types belong to another assembly and pricing belongs to one module. Making CS8509 an error is worth it for enum switches written without discard arms, with CS8524 kept a warning; for type switches it only forces the discard arm.

code

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

Shipment[] batch = [new Parcel(2), new Pallet(300), new Letter()];
foreach (var shipment in batch)
{
    try { Console.WriteLine(Rate(shipment)); }
    catch (SwitchExpressionException ex) { Console.WriteLine($"no rate for {ex.UnmatchedValue}"); }
}

// Warns CS8509 ("the pattern '_' is not covered") before and after Letter was added.
static decimal Rate(Shipment shipment) => shipment switch
{
    Parcel p => 5m + p.Kg,
    Pallet p => 80m + p.Kg / 10m,
};

abstract class Shipment { }
sealed class Parcel(int kg) : Shipment { public int Kg => kg; }
sealed class Pallet(int kg) : Shipment { public int Kg => kg; }
sealed class Letter : Shipment { }

go deeper

for a junior

Know that adding a subclass breaks the build only where an abstract member is missing, not at switch expressions.

for a middle

Explain why CS8509 names the pattern _ for a switch over a class hierarchy, and what CS0534 checks.

for a senior

Trace a SwitchExpressionException for a new type back to the switch expressions that need an arm, and make their discard arms throw.

for a principal

Decide per area whether types or operations change more often, set the CS8509 and CS8524 policy, and write it into the coding standard.

## The decision A shipping service prices three kinds of shipment, `Parcel`, `Pallet` and now `Letter`, all derived from an abstract `Shipment`. The team has two C# shapes for the pricing logic and one build-policy question. This is a judgment call: both shapes are correct C#, and the right one depends on how the code changes. ## What the compiler guarantees for each shape **Virtual dispatch.** `Shipment` declares `public abstract decimal Rate();` and each class overrides it. When someone adds `Letter` without an override, the build fails: ```plaintext error CS0534: 'Letter' does not implement inherited abstract member 'Shipment.Rate()' ``` **Switch expression.** One method holds the rule: `shipment switch { Parcel p => ..., Pallet p => ... }`. The compiler reports, **before `Letter` exists**: ```plaintext warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. ``` The compiler does not treat a class hierarchy as closed, even when the base class is abstract and every derived class is sealed, because nothing stops another class from deriving from `Shipment`. So every type switch over classes needs a discard arm or lives with the warning, and when `Letter` is added the diagnostics do **not change**. `Letter` reaches the discard arm, or throws `SwitchExpressionException` if there is none. | Concern | Abstract `Rate()` | Switch expression over types | |---|---|---| | New shipment type | Error CS0534 until implemented | Compiles; discard arm or run-time throw | | New operation (customs fee, label size) | Edit every class | One new method in one place | | Types from another assembly | Needs the owner to change them | Works without touching them | | Logic location | Spread across the types | Together in one module | ## Choosing The trade is the classic one between adding types and adding operations, expressed in C# diagnostics: - **Prefer virtual or abstract members** when new kinds of shipment arrive more often than new pricing questions, and when the types are yours to change. CS0534 is a compile-time checklist for every new type. - **Prefer switch expressions** when many operations (pricing, customs, labelling, carrier selection) are each owned by a different module, when the types are plain records shared across modules, or when they come from a library you cannot modify. - **Mixing is fine**: a core abstract member for behaviour every type must define, plus switch expressions for module-local policies that read the types. When the team chooses switch expressions, it should decide what the discard arm does. `_ => throw new ArgumentOutOfRangeException(nameof(shipment))` turns a forgotten type into a loud failure on first use; a discard arm that returns a fallback price turns it into silent revenue loss. ## Should CS8509 fail the build? The value of the warning differs by input: 1. **Enum switches.** Written without a discard arm, CS8509 names each new member (`OrderStatus.Cancelled`) at every switch that misses it. Making CS8509 an error turns an enum addition into a compile-time checklist, the same benefit CS0534 gives types. 2. **CS8524**, the unnamed-enum-value warning, should **not** become an error alongside it: it can only be satisfied with a catch-all arm, and that arm silences CS8509 for the next member too. Teams keep it a warning or suppress it and let unnamed values throw `SwitchExpressionException`. 3. **Type switches.** The rule only forces the discard arm that the hierarchy needs anyway, so it adds little protection there. 4. **Integers and strings.** A catch-all is nearly always needed; the error keeps people from forgetting it. How a project sets `WarningsAsErrors`, `NoWarn` or `.editorconfig` severities is covered with compiler warnings and analyzers. ## What C# 14 gives you today In C# 14 (closed hierarchies exist only as a C# 15 preview), the compiler's help comes down to three facts: - Type switches over classes get **no** compile-time help for new types. - Abstract members get **full** compile-time help for new types. - Enum switches get help for new **named** members only when they have no discard arm. Document the choice in the team's coding standard so reviewers know which signal each switch is supposed to give.

  • Why does a switch expression over `Parcel p` and `Pallet p` warn CS8509 even though every concrete subclass of the abstract `Shipment` has an arm?
    The compiler does not treat the set of classes deriving from `Shipment` as fixed: another class could derive from it later, in this assembly or another. A type pattern for each known subclass never adds up to the whole hierarchy, and the warning names `_` as the uncovered pattern.
  • If the team keeps type switches, how do you stop a new shipment type from being priced silently?
    Make the discard arm throw, for example `_ => throw new ArgumentOutOfRangeException(nameof(shipment))`, never return a fallback price, and add a test that enumerates the derived types by reflection and calls each switch with one instance. The compiler cannot do this check today.

  • Claiming the compiler proves a type switch exhaustive when every subclass is sealed
  • Expecting a new subclass to trigger a fresh CS8509 at each type switch
  • Making CS8524 an error alongside CS8509 for enum switches
  • Assuming a discard arm that throws is checked by the compiler for new types
  • Giving a type switch a discard arm that returns a fallback price