Skip to content
Mike Clift edited this page Dec 16, 2023 · 2 revisions

Adding Stateless to a project

Stateless is distributed as a NuGet package. Common ways you can add it to your project include using the Package Manager Console in Visual Studio and using the dotnet command line interface, as follows.

$ dotnet add package Stateless

Once added to your project, you can start using it by including the namespace in your source file.

using Stateless;

Components of a state machine with Stateless

To create a state machine, you'll need to define some states and at least one trigger. These are often declared as enums. For example:

public enum State
{
    On,
    Off
}

public enum Trigger
{
    Pressed
}

The state machine is instantiated with the state and trigger types as the generic type arguments, and the initial state as its constructor argument. This example models an on/off switch that starts in the Off state:

var lightSwitch = new StateMachine<State, Trigger>(State.Off);

Finally, define the state transitions that you want to allow based on your trigger type.

lightSwitch.Configure(State.Off).Permit(Trigger.Pressed, State.On);
lightSwitch.Configure(State.On).Permit(Trigger.Pressed, State.Off);

You could demo this state machine using a simple loop in a console application.

Console.WriteLine("Press space to change state");
while (true)
{
    Console.WriteLine($"Current state: {lightSwitch.State}");
    var pressed = Console.ReadKey(true).KeyChar;
    if (pressed != ' ')
    {
        break;
    }

    lightSwitch.Fire(Trigger.Pressed);
}

State and trigger types

Although states and triggers are often declared as enum types, they don't need to be. The OnOffExample example project shows a similar example to the one shown above, but its states are defined as strings and its trigger uses char.