BehavioralC#verifiedVerified

Command Pattern in C#

Encapsulates a request as an object, allowing you to parameterize clients, queue or log requests, and support undoable operations.

How to Implement the Command Pattern in C#

1Step 1: Define the command interface

public interface ICommand
{
    void Execute();
    void Undo();
}

2Step 2: Receiver performs the actual work

public class TextEditor
{
    public string Content { get; set; } = "";

    public void Insert(string text) => Content += text;
    public void Delete(int count) =>
        Content = Content[..^Math.Min(count, Content.Length)];
}

3Step 3: Concrete command

public class InsertTextCommand(TextEditor editor, string text) : ICommand
{
    public void Execute() => editor.Insert(text);
    public void Undo() => editor.Delete(text.Length);
}

4Step 4: Invoker manages command history

public class CommandHistory
{
    private readonly Stack<ICommand> _history = new();

    public void ExecuteCommand(ICommand command)
    {
        command.Execute();
        _history.Push(command);
    }

    public void UndoLast()
    {
        if (_history.TryPop(out var command))
            command.Undo();
    }
}

Command Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Command Pattern in the Real World

Think of a restaurant order ticket. A waiter (invoker) takes your order and writes it on a slip (command). The slip is handed to the kitchen (receiver) which executes it. The waiter doesn't cook anything—they just carry and deliver orders. Tickets can be queued, cancelled before cooking, or reviewed in an audit log at day's end.