C# › Enums & Flags

How would you use pattern matching (switch expressions) with an enum, including exhaustiveness warnings from the compiler?

Advanced

Answer

A switch expression over an enum lets you handle each member concisely and return a value directly; the compiler emits a WARNING (not an error, unlike some other languages) if you don't handle every enum member and lack a discard pattern, helping catch forgotten cases when new members are added later.
public enum OrderStatus { Pending, Shipped, Delivered, Cancelled }

string Describe(OrderStatus status) => status switch {
  OrderStatus.Pending => "Waiting to ship",
  OrderStatus.Shipped => "On its way",
  OrderStatus.Delivered => "Arrived",
  OrderStatus.Cancelled => "Order cancelled",
  _ => throw new ArgumentOutOfRangeException(nameof(status)) // catches truly invalid/undefined values
};
Real-world example Mapping an OrderStatus enum to a user-facing display string, with the compiler helping catch forgotten cases as the enum evolves.

Common follow-ups: Why is it good practice to throw in the discard '_' case rather than silently returning a default value?