C# › Design Patterns in C#
How would you implement the Strategy pattern in C# using either interfaces or delegates?
IntermediateAnswer
Define a common interface (or a delegate type) representing an interchangeable algorithm, implement multiple concrete strategies, and inject/pass the chosen one into the context class — modern C# often prefers a simple Func<> delegate over a full interface hierarchy for lightweight strategies.
// Interface-based
public interface IDiscountStrategy { decimal Apply(decimal price); }
public class PercentageDiscount : IDiscountStrategy {
public decimal Apply(decimal price) => price * 0.9m;
}
// Delegate-based (lighter weight)
Func<decimal, decimal> percentageDiscount = price => price * 0.9m;Real-world example Supporting multiple interchangeable pricing, sorting, or validation strategies that can be swapped at runtime.