3. Getting Started - iwannabebot/SharpFsm GitHub Wiki

📆 Installation

NuGet version (SharpWiki)

Supported .NET versions: .NET 6, .NET 8, .NET Standard 2.0, 2.1.

# .NET CLI
dotnet add package SharpFsm

# NuGet Package Manager
Install-Package SharpFsm

# Packet CLI
paket add SharpFsm

🛠️ Basic Example

Here's a minimal example of a switch with On and Off states:

using SharpFsm;

public enum SwitchState { Off, On }
public class SwitchContext { }

var builder = FiniteStateMachineBuilder<SwitchState, SwitchContext>.Create("Switch")
    .WithInitialState(SwitchState.Off)
    .AddTransition(SwitchState.Off, SwitchState.On).Done()
    .AddTransition(SwitchState.On, SwitchState.Off).Done();
var definition = builder.Build();
var fsm = new FiniteStateMachine<SwitchState, SwitchContext>(definition);
var context = new SwitchContext();

Console.WriteLine(fsm.Current); // Output: Off
fsm.TryTransitionTo(SwitchState.On, context);
Console.WriteLine(fsm.Current); // Output: On

🧠 Adding Transition Conditions

Transition guards allow you to conditionally permit or deny a state change based on runtime logic. This transition will only succeed during working hours (9 AM to 5 PM).

.AddTransition(SwitchState.Off, SwitchState.On)
    .When(ctx => DateTime.Now.Hour >= 9 && DateTime.Now.Hour <= 17)

You can write complex logic inside your transition logic like connecting from database, making API calls etc.

⚡ Adding Side Effects (On Transition)

You can attach side effects to transitions — useful for logging, triggering events, or updating services.

.AddTransition(SwitchState.On, SwitchState.Off)
    .WithSideEffect((ctx, _, _) =>
    {
        // Your code goes here
    })
```