BehavioralC#verifiedVerified

State Pattern in C#

Allows an object to alter its behavior when its internal state changes, appearing as if the object has changed its class.

How to Implement the State Pattern in C#

1Step 1: Define the state interface

public interface IState
{
    void Handle(Context context);
    string Name { get; }
}

2Step 2: Context delegates behavior to the current state

public class Context
{
    public IState CurrentState { get; private set; }

    public Context(IState initial) => CurrentState = initial;

    public void TransitionTo(IState state)
    {
        Console.WriteLine($"Transition: {CurrentState.Name} -> {state.Name}");
        CurrentState = state;
    }

    public void Request() => CurrentState.Handle(this);
}

3Step 3: Concrete states

public class IdleState : IState
{
    public string Name => "Idle";
    public void Handle(Context context)
    {
        Console.WriteLine("Idle: Starting work...");
        context.TransitionTo(new ActiveState());
    }
}

public class ActiveState : IState
{
    public string Name => "Active";
    public void Handle(Context context)
    {
        Console.WriteLine("Active: Finishing work...");
        context.TransitionTo(new IdleState());
    }
}

// Usage:
// var ctx = new Context(new IdleState());
// ctx.Request(); // Idle -> Active
// ctx.Request(); // Active -> Idle

State Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

State Pattern in the Real World

Think of a traffic light. The light itself (context) doesn't change its wiring, but its active state—red, yellow, or green—completely determines what drivers should do. Each color has its own rules, and the light transitions through states on a timer. Adding a flashing-yellow state only requires defining that state's rules, not rewiring the entire light.