Strategy intent and structure, replacing growing switch statements with interchangeable algorithms, .NET examples (IComparer<T>, IEqualityComparer<T>, StringComparer, JsonNamingPolicy), selecting strategies via IEnumerable<T>, a dictionary or keyed services, delegates as one-method strategies, and when a switch is still clearer.
Strategy puts each variant of an algorithm behind one interface, so the code that uses it (the context) calls whichever implementation it was given instead of branching on a mode. A switch that grows with every new discount, carrier or export format becomes a set of small classes, and adding a variant means adding a class, not editing the switch (Open/Closed).
.NET uses it everywhere: IComparer<T> in List<T>.Sort, IEqualityComparer<T> in Dictionary, StringComparer.OrdinalIgnoreCase, JsonNamingPolicy.
IEnumerable<IStrategy>, or use keyed services (.NET 8+), to pick one by key.Func<T, TResult> delegate is a strategy without the ceremony.The trade-off: more types and indirection, so a short, stable switch is often clearer.
"Strategy is about making an algorithm swappable. I define an interface for the part that varies, say
IDiscountStrategywith anApplymethod, write one class per variant, and the code that needs a discount just calls the interface. It doesn't know which variant it got. The payoff shows when the alternative is aswitchon discount type that's been copied into the cart, the invoice and the refund code: every new discount means editing all of them and retesting everything. With strategies, a new discount is one new class and one registration line, and the existing ones don't change.In .NET you use Strategy constantly without calling it that.
List<T>.Sorttakes anIComparer<T>,Dictionarytakes anIEqualityComparer<T>, andStringComparer.OrdinalIgnoreCaseis a ready-made strategy object. In application code I register every implementation against the same interface and injectIEnumerable<IDiscountStrategy>. Each strategy exposes aKey, and I build a dictionary once in the constructor, so lookup is O(1) and a duplicate key fails at start-up rather than at checkout. Since .NET 8, keyed services are the other option:AddKeyedSingleton<IDiscountStrategy, LoyaltyDiscount>("loyalty")and resolve by key. When the variant is one small function with no dependencies I skip the interface and pass aFunc<decimal, decimal>; a delegate is a one-method strategy.The mistake I see is going the other way: turning a three-case
switchthat hasn't changed in two years into an interface, three classes and a factory. That's ceremony, not design. I reach for Strategy when variants are added regularly, have their own dependencies, or need testing in isolation. Strategy pays off when the list of variants keeps growing; a stable list is fine as a switch."
| Role | In the discount example | In the framework |
|---|---|---|
| Strategy (interface) | IDiscountStrategy |
IComparer<T> |
| Concrete strategy | LoyaltyDiscount, SeasonalDiscount |
StringComparer.OrdinalIgnoreCase |
| Context | DiscountService |
List<T>.Sort, Dictionary<TKey,TValue> |
| Mechanism | Example | Good for |
|---|---|---|
| Method parameter | list.Sort(comparer) |
Caller decides per call |
| Constructor injection of one strategy | PriceFormatter(Func<decimal,string> format) |
Fixed for the object's lifetime |
IEnumerable<IStrategy> + key dictionary |
DiscountService |
Choose per request from data |
| Keyed services (.NET 8+) | [FromKeyedServices("loyalty")] |
Key known at the injection site |
| Use Strategy when | Prefer a switch or if when |
|---|---|
| New variants arrive often | Two or three variants that rarely change |
| Variants need their own dependencies (rates, HTTP clients, clock) | Variants are one-line expressions |
| You want to unit test each variant alone | All branches are trivially covered by one test |
| The same branching is repeated in several places | It appears in exactly one place |
A checkout service had a switch on promotion type copied into the cart, invoice and refund paths. Moving to IPromotionStrategy keyed by promotion code cut the change for a new promotion from five files to one class plus one registration line. Promotion pricing defects dropped from about three per quarter to none over the next two quarters, because existing promotions were no longer edited when a new one shipped.
Checks that the candidate understands Strategy as swappable behaviour behind an interface, can wire several implementations in .NET DI, and knows when a switch or delegate is enough.
Green flags
IComparer<T> or IEqualityComparer<T>.IEnumerable<T> or keyed services.Red flags
Client βββΆ Context ββ strategy: IStrategy
Execute() { ... strategy.Apply(input) ... }
β
Β«interfaceΒ» IStrategy
+ Apply(input)
β² β² β²
StrategyA StrategyB StrategyC
The context owns the workflow; the strategy owns one decision or calculation inside it. The client (or the DI container) decides which strategy the context gets.
| API | The strategy | Swapped how |
|---|---|---|
List<T>.Sort, Array.Sort, OrderBy |
IComparer<T> / Comparison<T> |
Parameter |
Dictionary, HashSet |
IEqualityComparer<T> |
Constructor |
StringComparer.Ordinal, OrdinalIgnoreCase |
Ready-made comparers | Static instances |
JsonSerializerOptions.PropertyNamingPolicy |
JsonNamingPolicy |
Options property |
| ASP.NET Core Identity | IPasswordHasher<TUser> |
DI replacement |
PriorityQueue<TElement,TPriority> |
IComparer<TPriority> |
Constructor |
Recognising these matters in interviews: a candidate who says "Strategy is when you pass a comparer to Sort" understands the pattern better than one who recites the UML.
The built-in container supports multiple registrations of one service type:
IDiscountStrategy returns the last registration.IEnumerable<IDiscountStrategy> returns all of them, in registration order.So the usual shape is: each strategy exposes a Key, the context receives the enumerable and builds a dictionary once. ToDictionary throws ArgumentException on a duplicate key, which turns a copy-paste mistake into a start-up failure. Wrapping it in ToFrozenDictionary (.NET 8+) gives faster reads for a set that never changes.
Keyed services (.NET 8+) move the key into the container: AddKeyedSingleton<IDiscountStrategy, LoyaltyDiscount>("loyalty"), then [FromKeyedServices("loyalty")] in a constructor or sp.GetRequiredKeyedService<IDiscountStrategy>(key). That works well when the key is known where you inject; when it comes from request data, resolving by key at run time drifts towards a service locator, and the dictionary approach is cleaner.
Comparison<T>, Func<T, TResult> and Predicate<T> are strategies without a named type. list.Sort((a, b) => a.Price.CompareTo(b.Price)) is the pattern in one line. Prefer a delegate when the variant is a single function with no dependencies; prefer an interface when there are several related methods, dependencies to inject, or you want the variants discoverable as named classes. Lambdas that capture variables allocate a closure object and a delegate; static lambdas guarantee no capture.
| Pattern | Who chooses the behaviour | Changes during the object's life? |
|---|---|---|
| Strategy | The client or the container, from outside | Usually not |
| State | The object itself, as its state changes | Yes, on each transition |
| Template Method | A subclass, at compile time | No |
List<Product> three ways: an IComparer<Product> class, a Comparison<Product> lambda, and OrderBy. Note which allocate.IDiscountStrategy implementations, inject a single IDiscountStrategy, and check which one you get. Then inject IEnumerable<IDiscountStrategy>.Key and confirm the dictionary throws at start-up.Before: a switch that every new discount edits. After: strategies selected by key, plus a delegate for the simple case.
namespace Billing;
public enum DiscountType { None, Seasonal, Loyalty }
// Before: grows with every promotion, and this switch is copied into refunds and invoices too
public static class DiscountCalculator
{
public static decimal Apply(DiscountType type, decimal total) => type switch
{
DiscountType.None => total,
DiscountType.Seasonal => total * 0.90m,
DiscountType.Loyalty => Math.Max(0m, total - 5m),
_ => throw new ArgumentOutOfRangeException(nameof(type))
};
}
namespace Billing;
using System.Collections.Frozen;
public interface IDiscountStrategy
{
string Key { get; }
decimal Apply(decimal total);
}
public sealed class NoDiscount : IDiscountStrategy
{
public string Key => "none";
public decimal Apply(decimal total) => total;
}
// A strategy with its own dependency: easy to test with a FakeTimeProvider
public sealed class SeasonalDiscount(TimeProvider clock) : IDiscountStrategy
{
public string Key => "seasonal";
public decimal Apply(decimal total) =>
clock.GetUtcNow().Month is 11 or 12 ? total * 0.90m : total;
}
public sealed class LoyaltyDiscount : IDiscountStrategy
{
public string Key => "loyalty";
public decimal Apply(decimal total) => Math.Max(0m, total - 5m);
}
// The context: builds the lookup once; ToDictionary throws on a duplicate key at start-up
public sealed class DiscountService(IEnumerable<IDiscountStrategy> strategies)
{
private readonly FrozenDictionary<string, IDiscountStrategy> _byKey = strategies
.ToDictionary(s => s.Key, StringComparer.OrdinalIgnoreCase)
.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
public decimal Apply(string key, decimal total) =>
_byKey.TryGetValue(key, out var strategy)
? strategy.Apply(total)
: throw new KeyNotFoundException($"No discount strategy '{key}'.");
}
// Program.cs: one line per strategy; a new discount touches nothing else
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<IDiscountStrategy, NoDiscount>();
builder.Services.AddSingleton<IDiscountStrategy, SeasonalDiscount>();
builder.Services.AddSingleton<IDiscountStrategy, LoyaltyDiscount>();
builder.Services.AddSingleton<DiscountService>();
// Keyed alternative (.NET 8+) when the key is known at the injection site:
// builder.Services.AddKeyedSingleton<IDiscountStrategy, LoyaltyDiscount>("loyalty");
// public sealed class LoyaltyReport([FromKeyedServices("loyalty")] IDiscountStrategy discount) { ... }
// Delegates as lightweight strategies: no interface needed for one function
List<(string Name, decimal Price)> items = [("Kettle", 49m), ("Toaster", 39m)];
items.Sort(static (a, b) => a.Price.CompareTo(b.Price)); // Comparison<T> is the strategy
Func<decimal, decimal> gst = static net => net * 1.10m; // swap for a zero-rated export
IDiscountStrategy when several are registered. Why it is wrong: The container silently returns the last registration, so every request gets the same strategy. Instead: Inject IEnumerable<IDiscountStrategy> and select by key, or use keyed services.strategies.FirstOrDefault(s => s.Key == key) on every request. Why it is wrong: It is O(n) per call, and a duplicate key quietly picks the first match. Instead: Build a dictionary once with ToDictionary (throws on duplicates) and optionally freeze it.switch into a factory that does new LoyaltyDiscount(). Why it is wrong: The switch is still there and still edited for every variant, so nothing was gained. Instead: Let DI enumerate the registered strategies.switch into an interface, three classes and a factory. Why it is wrong: It adds files and indirection with no change to absorb. Instead: Keep a switch expression until variants start to grow or need dependencies.NullReferenceException or returning 0 for an unknown key. Why it is wrong: Bad data turns into wrong prices or confusing errors. Instead: Throw a clear exception, return a validation error, or use an explicit default strategy.Strategy is the pattern I'd defend most often in a code review, and also the one I'd most often push back on. The test is change frequency: if the variants are added every sprint, own dependencies or are owned by different people, strategies isolate them and make each testable alone. If the list is fixed, a switch expression with exhaustiveness checking is shorter, faster to read and catches missing cases at compile time when you switch on an enum.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Switch expression | Few, stable variants, no dependencies | Edits one place per variant | Variants grow or are repeated in several places |
Func<> / Comparison<> delegate |
One function, no dependencies | Closure allocation if it captures | Several related methods or injected services |
Interface + IEnumerable<T> + dictionary |
Variants chosen per request from data | One class per variant | Two variants that never change |
| Keyed services (.NET 8+) | Key fixed at the injection site | Key strings in registration | Key comes from request data (becomes service locator) |
The framework already gives you the strategy hooks for sorting, equality, naming and hashing; write your own only for your domain's variation points. To judge whether a refactor helped, count how many files a new variant touches before and after.
The Open/Closed Principle says modules should be open for extension but closed for modification: you add new behaviour by adding code, not by editing tested code. In C# this usually means a strategy interface with one implementation per variant, registered in DI, so adding a new payment method is a new class rather than another case in a growing switch. I apply it where change actually happens repeatedly. A small, stable switch (or a switch expression over a closed set) is fine; building extension points for variants that never arrive is speculative generality.
Func is a delegate that returns a value, so Func<int, string> takes an int and returns a string. Action returns void, and Predicate<T> is a delegate that takes a T and returns bool. Older APIs like List<T>.FindAll use it, while LINQ uses Func<T, bool>. Even with identical signatures they are different delegate types, so you cannot pass a Func<T, bool> variable as a Predicate<T> without wrapping it. A lambda converts to either. I declare my own delegate only when I need ref or out parameters or a meaningful name.
Composition means a class has other objects as parts and delegates work to them, instead of inheriting behaviour. A Car has an Engine and Wheels; an OrderProcessor has a validator, a pricer and a notifier. In the strict UML sense, composition also means ownership: the parts are created and destroyed with the whole and are not shared. Benefits: behaviour can be swapped (pass a different IPricingStrategy), combined freely (decorators wrap each other), tested in isolation, and changed without a fragile base class. The cost is a little more wiring, usually handled by constructors or dependency injection.
I'd refactor in safe steps. First, characterisation tests that pin today's prices for each carrier. Then extract IShippingStrategy with a Carrier key and Calculate(Parcel), and move each case into its own class with its own dependencies (rates from IOptions<T>, a remote-postcode lookup). The calculator becomes a context that receives IEnumerable<IShippingStrategy>, builds a dictionary once (a duplicate key throws at start-up) and returns a validation error for unknown carriers.
That satisfies Open/Closed: a new carrier is one class plus one registration line, and the existing carriers and the context don't change. Each strategy gets its own unit test, plus one test that builds the real container and checks every carrier is registered.
The trade-off is more types: for two or three stable one-line formulas, I'd keep the switch.
Last updated 18 Nov 2026.