-
Notifications
You must be signed in to change notification settings - Fork 769
Getting started
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;
To create a state machine, you'll need to define some states and at least one trigger. These are often declared as enum
s. 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);
}
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 string
s and its trigger uses char
.