Tutorials Design Patterns in C#
State Pattern — Complete Guide
State Pattern — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.
On this page
Design Patterns in C# · Lesson 20 of 69
State Pattern
GoF Core ✓ → Enterprise → Cloud & Craft
Enterprise · 2 — App patterns · ~6 min · Module 3: Behavioral Design Patterns
What is this?
State pattern moves state-specific behavior into state objects so the context delegates instead of giant switch statements.
Why should you care?
ShopNest orders (Pending → Paid → Shipped → Cancelled) have different allowed actions per state.
See it live — copy this example
Paste into a C# console or class library project and run dotnet run.
public interface IOrderState { void Pay(Order o); void Ship(Order o); }
public sealed class Order
{
public IOrderState State { get; set; } = new PendingState();
public void Pay() => State.Pay(this);
public void Ship() => State.Ship(this);
}
public sealed class PendingState : IOrderState
{
public void Pay(Order o) { Console.WriteLine("paid"); o.State = new PaidState(); }
public void Ship(Order o) => Console.WriteLine("cannot ship yet");
}
public sealed class PaidState : IOrderState
{
public void Pay(Order o) => Console.WriteLine("already paid");
public void Ship(Order o) { Console.WriteLine("shipped"); o.State = new ShippedState(); }
}
public sealed class ShippedState : IOrderState
{
public void Pay(Order o) => Console.WriteLine("noop");
public void Ship(Order o) => Console.WriteLine("already shipped");
}
var order = new Order();
order.Pay();
order.Ship();
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- PendingState allows Pay; PaidState allows Ship.
- Transitions assign a new state object.
- Illegal calls become no-ops or errors inside the state.
Practice next
- Pay then Ship successfully.
- Try Ship first and see refusal.
- Add CancelledState.
- Throw on illegal Ship from Pending.
- Log every transition.
Remember
Behavior per state object. Clear transitions. Replace mega-switches.
ShopNest order lifecycle
Domain Order delegates to state objects.
Outcome: Illegal transitions blocked in one place.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!