State pattern applied to an order aggregate: (state, trigger) switch-expression transition tables, State classes when behaviour differs per state, the Stateless library (5.20.1) with Permit/PermitIf, external state storage, OnEntry, CanFire and graph export, returning 409 for invalid transitions, persisting the status with EF Core and a rowversion concurrency token, and testing transitions.
The State pattern makes behaviour depend on the current state and makes transitions explicit, so "ship a cancelled order" is rejected rather than a status field being overwritten.
Three implementations, from lightest:
(state, trigger): a compact, readable transition table; anything not listed is rejected.IOrderState per state): worth it when each state has substantial behaviour of its own.Permit, PermitIf guards, OnEntry actions, CanFire, and graph export, with external state storage so EF Core persists a plain Status column.Invalid transitions return 409 Conflict. Because two requests can both pass the check in memory, add a rowversion concurrency token so the second SaveChanges fails. The trade-off: a library and classes buy guards and visualisation at the cost of indirection; a switch table is often enough.
"The bug a state machine prevents is the one where any code path can set
order.Status = Shipped, including on an order that was cancelled ten minutes ago. So the first thing I'd do is makeStatusprivate-set on the aggregate and only change it through methods named after the triggers:Pay,Ship,Deliver,Cancel. Each method asks one question: is this trigger allowed from the current state? If not, it's a domain error, which the API turns into a 409 Conflict, not a 500.For how to express the rules, I'd start with the lightest option that's readable. A switch expression on the tuple
(Status, trigger)is a transition table in about ten lines:(Pending, Pay) => Paid,(Paid, Ship) => Shipped,(Pending or Paid, Cancel) => Cancelled, and a discard arm that rejects everything else. If each state carries real behaviour, say a paid order can be partially refunded and a shipped order can be re-routed, then State classes are clearer: anIOrderStateper state, each implementing only what it allows. When the machine grows guards, entry actions and a lot of states, I'd use Stateless: the current version is 5.20.1, released in February 2026, and it's actively maintained. You configurePermitandPermitIfper state, hookOnEntryto raise a domain event, askCanFireto drive the UI's buttons, and export a DOT or Mermaid graph for the business to review. Its external-storage constructor reads and writes myStatusproperty, so EF Core just persists a column.The mistake I see is stopping at the in-memory check. Two requests load the same Paid order: one cancels, one ships, both checks pass, both save. Adding a
rowversionconcurrency token means the secondSaveChangesthrowsDbUpdateConcurrencyException, and I return 409 and let the client reload. A state machine protects transitions in memory; the concurrency token protects them in the database. You need both."
| From \ Trigger | Pay | Ship | Deliver | Cancel |
|---|---|---|---|---|
| Pending | Paid | β | β | Cancelled |
| Paid | β | Shipped | β | Cancelled |
| Shipped | β | β | Delivered | β |
| Delivered | β | β | β | β |
| Cancelled | β | β | β | β |
| Switch expression table | State classes | Stateless | |
|---|---|---|---|
| Best for | Pure transitions, few states | Behaviour differs a lot per state | Guards, entry/exit actions, many states, visualisation |
| Rules live | One expression | Spread across classes | Fluent configuration |
| Guards | when clauses |
Code in each class | PermitIf(trigger, dest, guard) |
| Introspection | Write it yourself | Write it yourself | CanFire, PermittedTriggers, GetInfo() |
| Dependency | None | None | NuGet package |
| Concern | Approach |
|---|---|
| Column | Store Status as a string (HasConversion<string>()) so data stays readable after enum reordering |
| Encapsulation | Private setter; transitions only through methods |
| Concurrency | [Timestamp] byte[] RowVersion (SQL Server rowversion); catch DbUpdateConcurrencyException β 409 |
| Side effects | Raise a domain event on transition; publish through an outbox, not inline |
An order service let three different endpoints set Status directly, and about 0.3% of cancelled orders still went to the warehouse, roughly 40 a week at peak. Moving transitions into the aggregate with a switch-expression table and a rowversion token brought shipped-after-cancel incidents to zero; the concurrency check caught about 15 racing requests a week, which now returned 409 and were retried by the client.
Checks whether the candidate can model a lifecycle with explicit transitions, choose a proportionate implementation, and handle persistence and concurrency.
Green flags
Red flags
Order (context) ββ state: IOrderState
Pay() βββΆ state = state.Pay(this)
Ship() βββΆ state = state.Ship(this)
Β«interfaceΒ» IOrderState: Pay, Ship, Deliver, Cancel
β² β² β² β²
Pending Paid Shipped Cancelled
(Pay, Cancel) (Ship, (Deliver) (nothing)
Cancel)
The context delegates to its current state object, and the state object returns the next state. Unlike Strategy, the behaviour is chosen by the object itself and changes over its lifetime.
C# tuple patterns make a table readable:
(Status, trigger) switch
{
(Pending, Pay) => Paid,
(Pending or Paid, Cancel) => Cancelled,
...
_ => reject
}
The compiler can't check that every meaningful pair is listed (the discard arm makes it exhaustive), so a table-driven test over all state Γ trigger pairs is the safety net. Guards go in when clauses: (Delivered, Refund) when DaysSinceDelivery <= 30 => Refunded.
If states differ only in which transitions are allowed, classes add files without adding clarity. They earn their place when each state has its own behaviour: calculating what can be refunded, which fields can be edited, what the customer sees. A good test: if you'd write if (Status == ...) inside more than two or three methods, the behaviour belongs on state objects.
machine.Configure(OrderStatus.Paid).Permit(OrderTrigger.Ship, OrderStatus.Shipped).Permit(OrderTrigger.Cancel, OrderStatus.Cancelled).PermitIf(trigger, dest, () => condition, "description"); the description appears in graphs and errors.OnEntry, OnExit, OnEntryFrom(trigger, ...); async variants with OnEntryAsync and FireAsync.Fire throws InvalidOperationException by default; OnUnhandledTrigger lets you replace that with your own exception or a no-op.CanFire(trigger), PermittedTriggers (drive UI buttons), GetInfo() with UmlDotGraph.Format or the Mermaid exporter.Status property EF Core maps.Configuring a machine per entity instance costs a few allocations; for hot paths, cache the configuration in a static factory method or use the switch table.
Request A: load order (Paid, v1) ββ Cancel ββ SaveChanges (v1 β v2) β
Request B: load order (Paid, v1) ββ Ship ββ SaveChanges WHERE RowVersion = v1 β 0 rows β DbUpdateConcurrencyException
EF Core includes the original concurrency token in the UPDATE ... WHERE clause; zero rows affected means someone else changed the row. Return 409 and let the client reload, or retry the whole load-check-save once.
Entering Shipped usually triggers a notification or a warehouse message. Raise a domain event from the transition and publish it via an outbox in the same transaction, so a rolled-back transition never sends an email.
[Theory] over every (state, trigger) pair asserting allowed or rejected.Refund trigger allowed within 30 days of delivery using a when guard and TimeProvider.DbContext instances and confirm the second throws DbUpdateConcurrencyException.The aggregate with a switch-expression transition table, a rowversion token and a 409 for invalid transitions.
namespace Orders;
using System.ComponentModel.DataAnnotations;
public enum OrderStatus { Pending, Paid, Shipped, Delivered, Cancelled }
public enum OrderTrigger { Pay, Ship, Deliver, Cancel }
public sealed class InvalidTransitionException(OrderStatus from, OrderTrigger trigger)
: Exception($"Cannot {trigger} an order that is {from}.")
{
public OrderStatus From { get; } = from;
public OrderTrigger Trigger { get; } = trigger;
}
public sealed class Order
{
public Guid Id { get; private set; } = Guid.NewGuid();
public OrderStatus Status { get; private set; } = OrderStatus.Pending; // only transitions change it
[Timestamp] public byte[] RowVersion { get; private set; } = []; // SQL Server rowversion
public void Pay() => Fire(OrderTrigger.Pay);
public void Ship() => Fire(OrderTrigger.Ship);
public void Deliver() => Fire(OrderTrigger.Deliver);
public void Cancel() => Fire(OrderTrigger.Cancel);
public bool CanFire(OrderTrigger trigger) => Next(Status, trigger) is not null;
private void Fire(OrderTrigger trigger) =>
Status = Next(Status, trigger) ?? throw new InvalidTransitionException(Status, trigger);
// The whole lifecycle in one readable table; anything unlisted is rejected
private static OrderStatus? Next(OrderStatus from, OrderTrigger trigger) => (from, trigger) switch
{
(OrderStatus.Pending, OrderTrigger.Pay) => OrderStatus.Paid,
(OrderStatus.Paid, OrderTrigger.Ship) => OrderStatus.Shipped,
(OrderStatus.Shipped, OrderTrigger.Deliver) => OrderStatus.Delivered,
(OrderStatus.Pending or OrderStatus.Paid, OrderTrigger.Cancel) => OrderStatus.Cancelled,
_ => null
};
}
// EF Core mapping and the endpoint: invalid transition β 409, lost race β 409
namespace Orders;
using Microsoft.EntityFrameworkCore;
public sealed class OrdersDbContext(DbContextOptions<OrdersDbContext> options) : DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder b) =>
b.Entity<Order>().Property(o => o.Status).HasConversion<string>().HasMaxLength(20); // readable, reorder-safe
}
public static class OrderEndpoints
{
public static void MapOrderEndpoints(this WebApplication app) =>
app.MapPost("/orders/{id:guid}/ship", async (Guid id, OrdersDbContext db, CancellationToken ct) =>
{
var order = await db.Orders.FindAsync([id], ct);
if (order is null) return Results.NotFound();
try
{
order.Ship();
await db.SaveChangesAsync(ct); // UPDATE ... WHERE Id = @id AND RowVersion = @original
return Results.NoContent();
}
catch (InvalidTransitionException ex)
{
return Results.Problem(ex.Message, statusCode: StatusCodes.Status409Conflict);
}
catch (DbUpdateConcurrencyException)
{
return Results.Problem("The order was changed by another request. Reload and retry.",
statusCode: StatusCodes.Status409Conflict);
}
});
}
// The same lifecycle with Stateless 5.20.1, storing state on the entity
namespace Orders;
using Stateless;
public sealed class StatelessOrder
{
public OrderStatus Status { get; private set; } = OrderStatus.Pending;
public bool IsPaidInFull { get; set; }
private readonly StateMachine<OrderStatus, OrderTrigger> _machine;
public StatelessOrder()
{
_machine = new StateMachine<OrderStatus, OrderTrigger>(() => Status, s => Status = s); // external storage
_machine.Configure(OrderStatus.Pending)
.Permit(OrderTrigger.Pay, OrderStatus.Paid)
.Permit(OrderTrigger.Cancel, OrderStatus.Cancelled);
_machine.Configure(OrderStatus.Paid)
.PermitIf(OrderTrigger.Ship, OrderStatus.Shipped, () => IsPaidInFull, "paid in full")
.Permit(OrderTrigger.Cancel, OrderStatus.Cancelled);
_machine.Configure(OrderStatus.Shipped)
.Permit(OrderTrigger.Deliver, OrderStatus.Delivered)
.OnEntry(() => Console.WriteLine($"Order shipped")); // raise a domain event here in real code
_machine.OnUnhandledTrigger((state, trigger) => throw new InvalidTransitionException(state, trigger));
}
public void Fire(OrderTrigger trigger) => _machine.Fire(trigger);
public bool CanFire(OrderTrigger trigger) => _machine.CanFire(trigger);
public IEnumerable<OrderTrigger> PermittedTriggers => _machine.PermittedTriggers; // drive UI buttons
public string ToDotGraph() => Stateless.Graph.UmlDotGraph.Format(_machine.GetInfo());
}
// Table-driven test over every (state, trigger) pair
namespace Orders.Tests;
public class OrderTransitionTests
{
public static TheoryData<OrderStatus, OrderTrigger, OrderStatus?> Cases => new()
{
{ OrderStatus.Pending, OrderTrigger.Pay, OrderStatus.Paid },
{ OrderStatus.Pending, OrderTrigger.Ship, null },
{ OrderStatus.Paid, OrderTrigger.Ship, OrderStatus.Shipped },
{ OrderStatus.Paid, OrderTrigger.Cancel, OrderStatus.Cancelled },
{ OrderStatus.Cancelled, OrderTrigger.Ship, null },
{ OrderStatus.Delivered, OrderTrigger.Cancel, null },
};
[Theory, MemberData(nameof(Cases))]
public void Transitions_follow_the_table(OrderStatus from, OrderTrigger trigger, OrderStatus? expected)
{
var order = OrderInState(from);
if (expected is null)
Assert.Throws<InvalidTransitionException>(() => Fire(order, trigger));
else
{
Fire(order, trigger);
Assert.Equal(expected, order.Status);
}
}
private static void Fire(Order o, OrderTrigger t)
{
switch (t)
{
case OrderTrigger.Pay: o.Pay(); break;
case OrderTrigger.Ship: o.Ship(); break;
case OrderTrigger.Deliver: o.Deliver(); break;
case OrderTrigger.Cancel: o.Cancel(); break;
}
}
// Drive the aggregate through real transitions to reach a state
private static Order OrderInState(OrderStatus target)
{
var o = new Order();
switch (target)
{
case OrderStatus.Paid: o.Pay(); break;
case OrderStatus.Shipped: o.Pay(); o.Ship(); break;
case OrderStatus.Delivered: o.Pay(); o.Ship(); o.Deliver(); break;
case OrderStatus.Cancelled: o.Cancel(); break;
}
return o;
}
}
Status that any service can change. Why it is wrong: Nothing stops shipping a cancelled order. Instead: Private setter; transitions only through trigger methods that check the table.rowversion concurrency token and handle DbUpdateConcurrencyException.HasConversion<string>() or explicit numeric values.OnEntry. Why it is wrong: If SaveChanges then fails, the customer was told something that didn't happen. Instead: Raise a domain event and publish it through an outbox.The choice of implementation matters much less than two decisions around it: making the status impossible to change except through transitions, and protecting transitions against concurrent writers. I start with a switch table, move to State classes when per-state behaviour piles up, and adopt Stateless when guards, entry actions and visualisation for non-developers justify a dependency.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Switch expression table | Up to ~8 states, pure transitions | Guards and actions written by hand | Many guards, entry/exit actions, nested states |
| State classes | Behaviour differs substantially per state | One class per state | Only transition rules differ |
| Stateless | Guards, actions, hierarchy, graph export, CanFire for UI |
Dependency; per-instance configuration | A five-line table |
| Workflow engine / durable orchestration | Long-running, multi-service processes with timers | Infrastructure, operational complexity | A single aggregate's lifecycle |
I measure success by incidents (shipped-after-cancel, double refunds) and by how often DbUpdateConcurrencyException fires; a non-zero count proves the token is doing its job.
A switch expression returns a value: status switch { Paid => "Paid", _ => "Other" }. Each arm is a pattern, an optional when guard, and an expression. There's no fall-through or break, and the first matching arm wins. The result type comes from the arms or from the target. The compiler warns with CS8509 if it isn't exhaustive, and an unmatched value throws SwitchExpressionException. Switching on a tuple like (state, trigger) gives very readable state machines. When an arm needs several statements or side effects, a classic switch statement or polymorphism is clearer.
Strategy puts each variant of an algorithm behind one interface, so the code that uses it (the context) calls whichever implementation it was given instead of branching on a mode. A switch that grows with every new discount, carrier or export format becomes a set of small classes, and adding a variant means adding a class, not editing the switch (Open/Closed).
.NET uses it everywhere: IComparer<T> in List<T>.Sort, IEqualityComparer<T> in Dictionary, StringComparer.OrdinalIgnoreCase, JsonNamingPolicy.
IEnumerable<IStrategy>, or use keyed services (.NET 8+), to pick one by key.Func<T, TResult> delegate is a strategy without the ceremony.The trade-off: more types and indirection, so a short, stable switch is often clearer.
C# patterns now cover most data checks. There are type, constant and null patterns, relational ones like >= 100, logical and, or and not combinators, and property patterns, including extended ones like { Customer.Address.State: "NSW" }. There are also positional patterns that use Deconstruct, var and discard patterns, and list patterns like [first, .., last]. The compiler turns a switch into an efficient decision tree, warns when it isn't exhaustive, and errors on unreachable cases. I use patterns for closed sets of data shapes and polymorphism when new types keep being added.
How to tell it (STAR)
**S:** At [company], about [40] cancelled orders a week were still being shipped, and nobody could see an error. **T:** I needed to find out how and make it impossible. **A:** Using temporal-table history and Application Insights traces, I found cancel and ship requests racing on the same order, with three endpoints writing `Status` directly. I moved every transition into the order aggregate behind a switch-expression transition table, made the status private, added a `rowversion` token, and returned 409 for invalid or racing transitions. **R:** Shipped-after-cancel incidents dropped to [zero] within [a week], the concurrency check caught about [15] races a week that now resolve cleanly, and refund handling for that cause disappeared.
Last updated 18 Nov 2026.