C# › Design Patterns in C#
How would you implement the Chain of Responsibility pattern in C# to process a request through a series of independent handlers?
AdvancedAnswer
Each handler holds a reference to the NEXT handler in the chain; it either processes the request itself and stops, or passes it along to the next handler if it can't handle it — commonly implemented in ASP.NET Core's own middleware pipeline, which is essentially a real-world Chain of Responsibility implementation.
public abstract class ValidationHandler {
protected ValidationHandler? Next;
public ValidationHandler SetNext(ValidationHandler next) { Next = next; return next; }
public abstract bool Handle(Order order);
}
public class CreditCheckHandler : ValidationHandler {
public override bool Handle(Order order) =>
CheckCredit(order) && (Next?.Handle(order) ?? true);
}Real-world example Building a multi-step validation pipeline for an order (credit check, inventory check, fraud check) where each step can short-circuit the chain.