Skip to content

State Machine Transitions

Mikołaj Milewski edited this page Oct 27, 2026 · 1 revision

Transitions

Transition is the way to change state of State Machine.

In general, Transition consists of:

  • Trigger, type of Event that activates Transition,
  • Source, a State that transition is coming from,
  • Target, a State that transition is coming to,
  • Guard, logic that decides if Transition should happen,
  • Effect, logic that is run when Transition happens.

Types of Transitions

There are three types of Transitions:

  1. 'Regular' Transition that moves from one State to another,
  2. Internal Transition that has no Target State,
  3. Default Transition that has no explicit Trigger Event.

Transitions are always defined on the level of Source State.

Single State can have multiple Transitions triggered by various Event types. Moreover, there can be multiple Transitions triggered by the same Event type.

Definition

UML notation of Transition:

stateDiagram-v2
Source --> Target : Trigger [Guard] / Effect
Loading

Equivalent Stateflows notation of Transition:

Lambda style

Definition fragment (inside the builder callback):

    /* fragment of State Machine definition */
    .AddState("Source", b => b
        .AddTransition<Trigger>("Target", b => b
            .AddGuard(async c => true)
            .AddEffect(async c => {})
        )
    )
    .AddState("Target")

Using lambda style means that logic parts within Transition (Guard, Effect) are implemented directly in State Machine as lambdas.

Typed style

Definition fragment (inside the builder callback):

    /* fragment of State Machine definition */
    .AddState<Source>(b => b
        .AddTransition<Trigger, TriggerTransition, Target>()
    )
    .AddState<Target>()

Using typed style means that logic parts within Transition (Guard, Effect) are implemented as separate classes and referenced using typed overloads of Add* methods.

Structural event triggers

A transition can also match a registered structural event by name instead of a CLR event type. Register the event definition with AddEvents, then use the string overload of AddTransition. Its guard and effect receive StructuralEvent; read defined fields through Get<T>("fieldName").

using Stateflows.Common;
using Stateflows.Events;

builder.AddEvents(events => events
    .AddEvent("submit-order", e => e
        .AddField("orderId", FieldType.String)
        .AddField("quantity", FieldType.Int32)));

// In a State Machine definition:
.AddInitialState("Waiting", state => state
    .AddTransition("submit-order", "Accepted", transition => transition
        .AddGuard(c => c.Event.Get<int>("quantity") > 0)))
.AddState("Accepted")

The eventName must match the registered definition and the name on the event sent to the State Machine. The structural overload is not the generic AddTransition<TEvent> overload: its callback event is StructuralEvent. See Events for field definitions, event creation, validation, and structural requests.

The corresponding string-name variants are also available for internal and else transitions: AddInternalTransition(eventName, ...), AddElseTransition(eventName, targetStateName, ...), and AddElseInternalTransition(eventName, ...). As with the regular transition, their callbacks use StructuralEvent.

Exception triggers

State Machine exceptions that are not acknowledged by an IStateMachineExceptionHandler are sent back to that State Machine as events. A transition can handle one by using the exception type as its trigger:

.AddState("Working", state => state
    .AddTransition<IOException>("Failed"))
.AddState("Failed");

Exception triggers match the declared exception type and its derived types. For example, an IOException transition also matches a FileNotFoundException. This polymorphic matching is enabled automatically for exception-triggered transitions; do not assume it for ordinary event triggers. See State Machine exception handling for the exception-handler-before-event-routing order and the important distinction that routing an exception does not undo the failure of the original execution.

Else transitions

An else transition is a fallback among competing transitions in the same trigger-selection group. It is enabled only when the other candidate transitions for that group are not enabled. On a Choice or Junction, it is a default transition with no event trigger. A State can also define an event-triggered fallback with AddElseTransition<TEvent> or AddElseInternalTransition<TEvent>; these are considered when that event is processed.

.AddChoice("RouteOrder", choice => choice
    .AddTransition("Ship", transition => transition
        .AddGuard(async context => true))
    .AddElseTransition("Review"))

For a state-level event fallback:

public sealed record Approve(bool IsValid);

The following fragment belongs inside the relevant method or builder callback:

.AddState("Pending", state => state
    .AddTransition<Approve>("Approved", transition => transition
        .AddGuard(async context => context.Event.IsValid))
    .AddElseTransition<Approve>("Review"))

String-name overloads also support structural event names; see Structural Event Triggers. Else-transition evaluation and priority are covered in Evaluation of Transitions.

Logic

There are two places where logic can be injected into Transition of any type, both optional:

  1. Guard:
    • determines if Transition should happen,
    • must return bool value,
    • lack of Guard on Transition means that there is an implicit true-returning Guard,
    • should not cause any side effect,
    • can be called multiple times on multiple Transitions, even the ones which won't eventually happen.
  2. Effect:
    • is called when Transition happens, after OnExit of Source State and before OnEntry of Target State,
    • can cause side effects.

The way of adding logic to a Transition varies depending on the declaration style; the examples above show lambda and typed forms.

Evaluation

Topic is explained in Evaluation of Transitions.

Overview
Installation
Runtimes
   Orleans runtime
Concepts
   Events and Structural Events
   Messaging Patterns
   Validation
   Scheduling
   Observability
Behaviors
   Behavior Values
   Dependency Injection
   Behavioral Groups
   State Machines
       Concepts
           State Identity
           In-State Event Deferrals
           Evaluation of Transitions
           Exception Handling
       Building blocks
           Regions
           States
               State
               Composite State
               Orthogonal State
               Final State
           Pseudostates
               Choice
               Junction
               Fork
               Join
               History
           Transitions
               Transition
               Default Transition
               Internal Transition
   Activities
       Concepts
           Exception Handling
           Implicit Fork and Join
           Tokens
       Building blocks
           Nodes
               Action Node
               Decision Node
               Merge Node
               Initial Node
               Final Node
               Input Node
               Output Node
               Fork Node
               Join Node
               Accept Event Action Node
               Send Event Action Node
               Publish Event Action Node
               Time Event Action Node
               Data Store Node
               Structured Activity Node
               Iterative Activity Node
               Parallel Activity Node
           Flows
               Data Flow
               Control Flow
   Actions
   Entities
       Fields
       Mutations
       Projections
Extensions
   ClearScript
   FluentValidation
   JSON definitions
   Minimal APIs
   OneOf
   OpenTelemetry
   PlantUML
   Scheduling

Clone this wiki locally