BehavioralC#verifiedVerified

Chain of Responsibility Pattern in C#

Passes a request along a chain of handlers, where each handler decides to process it or pass it to the next handler in the chain.

How to Implement the Chain of Responsibility Pattern in C#

1Step 1: Define the request and abstract handler

public record Request(string Type, object Payload);

public abstract class Handler
{
    private Handler? _next;

    public Handler SetNext(Handler handler)
    {
        _next = handler;
        return handler;
    }

2Step 2: Handle or pass to next in chain

    public virtual string? Handle(Request request)
    {
        return _next?.Handle(request);
    }
}

3Step 3: Concrete handlers

public class AuthHandler : Handler
{
    public override string? Handle(Request request)
    {
        if (request.Type == "auth")
            return "AuthHandler: Handled authentication";
        return base.Handle(request);
    }
}

public class LoggingHandler : Handler
{
    public override string? Handle(Request request)
    {
        Console.WriteLine($"LoggingHandler: Logging {request.Type}");
        return base.Handle(request); // Always pass along
    }
}

public class DefaultHandler : Handler
{
    public override string? Handle(Request request) =>
        $"DefaultHandler: No specific handler for {request.Type}";
}

4Step 4: Build and use the chain

// var auth = new AuthHandler();
// var log = new LoggingHandler();
// var fallback = new DefaultHandler();
// auth.SetNext(log).SetNext(fallback);
// var result = auth.Handle(new Request("auth", null!));

Chain of Responsibility Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Chain of Responsibility Pattern in the Real World

Like a customer support escalation: your call starts with a front-line agent. If they can’t resolve it, they transfer you to a specialist. If the specialist can’t help, it goes to a manager. Each level either handles it or passes it up the chain.