Back to results for “Enums”
C# › Enums & Flags

How would you design an enum-based state machine using pattern matching to enforce valid state transitions at compile time or runtime?

Advanced

Answer

Represent states as an enum, and define an explicit transition-validation method (often using a switch expression matching CURRENT state and DESIRED next state as a tuple) that only allows specific, intentional transitions — throwing or returning false for any transition not explicitly permitted, preventing invalid state changes from silently succeeding.
public enum OrderState { Created, Paid, Shipped, Cancelled }

public bool CanTransition(OrderState from, OrderState to) => (from, to) switch {
  (OrderState.Created, OrderState.Paid) => true,
  (OrderState.Created, OrderState.Cancelled) => true,
  (OrderState.Paid, OrderState.Shipped) => true,
  (OrderState.Paid, OrderState.Cancelled) => true,
  _ => false // every other transition is explicitly disallowed
};
Real-world example Enforcing a valid order lifecycle (Created -> Paid -> Shipped) and rejecting invalid transitions like Shipped -> Created.

Common follow-ups: How would you extend this design to also carry data specific to each state, beyond what a plain enum alone can represent?