ZeroAlloc.StateMachine
Source-generated, zero-allocation finite state machines for .NET.
Add [StateMachine] and [Transition<TState, TTrigger>] to a partial class or struct. The generator emits a TryFire(TTrigger) method as a switch expression over (TState, TTrigger) tuples — no dictionary, no delegate dispatch, no heap allocation on the transition path.
Quick Example
[StateMachine(InitialState = nameof(State.Idle))]
[Transition<State, Trigger>(From = State.Idle, On = Trigger.Submit, To = State.Pending)]
[Transition<State, Trigger>(From = State.Pending, On = Trigger.Pay, To = State.Done)]
[Terminal<State>(State = State.Done)]
public partial class OrderMachine { }
var machine = new OrderMachine();
machine.TryFire(Trigger.Submit); // true — Idle → Pending
machine.Current; // Pending
Contents
| Page | Description |
|---|---|
| Getting Started | Install and define your first machine |
| Attributes | [StateMachine], [Transition], [Terminal] reference |
| Source Generator | What the generator emits — input/output examples |
| Testing | Unit-test state machines without mocking |
| AOT & Trimming | Native AOT compatibility |
| Performance | Benchmark results and allocation profile |
Core Concepts
| Page | Description |
|---|---|
| States and Triggers | Enums as states and triggers, naming conventions |
| Transitions | Directed edges, TryFire, ordering, entry/exit contract |
| Concurrent Mode | CAS loop, Volatile.Read, hook ordering, guard restrictions |
Guides
| Page | Description |
|---|---|
| Guards | Block transitions at runtime with When = true |
| Entry and Exit Actions | React to state crossings with partial void hooks |
| Terminal States | Intentional sinks and the [Terminal] attribute |
| Circuit Breaker Example | Real-world use: thread-safe circuit breaker |
Diagnostics
| ID | Severity | Description |
|---|---|---|
| ZSM0001 | Warning | Unreachable state |
| ZSM0002 | Warning | Unintentional sink state |
| ZSM0003 | Warning | Single-use trigger (possible typo) |
| ZSM0004 | Error | Concurrent mode on a struct |