📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

What is the Strategy pattern? Explain how it replaces a switch on a type or mode, how you register several strategies in DI and pick one at run time (IEnumerable<IStrategy> or keyed services), and when a plain delegate is a better, lighter-weight strategy.

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.

Junior Theory Intermediate delegates dependency-injection design-patterns open-closed strategy

🎯 Key points

  • Strategy puts each variant of an algorithm behind one interface; the context delegates to the implementation it holds instead of branching
  • Replaces a switch/if-else on a mode or type that is copied around and grows; a new variant is a new class plus one registration, existing code untouched (Open/Closed)
  • Each strategy is a small class testable in isolation with its own dependencies (e.g. a FakeTimeProvider), and the context is tested with fake strategies
  • Framework examples: IComparer<T> in List<T>.Sort, IEqualityComparer<T> in Dictionary, StringComparer.OrdinalIgnoreCase, JsonNamingPolicy.CamelCase
  • Register several implementations and inject IEnumerable<IStrategy>; build a dictionary by Key once (ToDictionary throws on duplicates at start-up)
  • Injecting a single IStrategy when several are registered silently gives the last registration, so every request gets the same behaviour
  • Keyed services (.NET 8+): AddKeyedSingleton<IStrategy, T>("key") with [FromKeyedServices]; a Func<T, TResult> delegate is a one-method strategy with no class
  • A switch expression is clearer when the variants are few, stable and have no dependencies

⏱ 30-second answer

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.

  • In DI, register several implementations and inject IEnumerable<IStrategy>, or use keyed services (.NET 8+), to pick one by key.
  • For one small function with no dependencies, a 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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Strategy is about making an algorithm swappable. I define an interface for the part that varies, say IDiscountStrategy with an Apply method, 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 a switch on 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>.Sort takes an IComparer<T>, Dictionary takes an IEqualityComparer<T>, and StringComparer.OrdinalIgnoreCase is a ready-made strategy object. In application code I register every implementation against the same interface and inject IEnumerable<IDiscountStrategy>. Each strategy exposes a Key, 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 a Func<decimal, decimal>; a delegate is a one-method strategy.

The mistake I see is going the other way: turning a three-case switch that 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."


Structure

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>

How the context gets its strategy

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

When to use it and when not

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

Production example

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.

πŸ” What the interviewer is checking

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

  • Names framework examples like IComparer<T> or IEqualityComparer<T>.
  • Knows that resolving one service gives the last registration and uses IEnumerable<T> or keyed services.
  • Mentions delegates as lightweight strategies.
  • Says when not to use it.

Red flags

  • Replaces the switch with a factory that still switches.
  • Puts mutable per-request state in singleton strategies.
  • Applies Strategy to every conditional.

πŸ“š Learn in depth

1. Structure

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.

2. Where the framework already uses it

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.

3. Selecting a strategy at run time

The built-in container supports multiple registrations of one service type:

  • Resolving IDiscountStrategy returns the last registration.
  • Resolving 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.

4. Delegates are one-method strategies

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.

5. Strategy vs its neighbours

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

6. Costs

  • One interface call per use: a few nanoseconds, and often devirtualised by dynamic PGO in .NET 10 when one implementation dominates.
  • One object per strategy: register stateless strategies as singletons.
  • More files and a level of indirection: a reader has to find which implementation runs for a given key.

Try it yourself

  1. Sort a List<Product> three ways: an IComparer<Product> class, a Comparison<Product> lambda, and OrderBy. Note which allocate.
  2. Register two IDiscountStrategy implementations, inject a single IDiscountStrategy, and check which one you get. Then inject IEnumerable<IDiscountStrategy>.
  3. Register two strategies with the same Key and confirm the dictionary throws at start-up.
  4. Rewrite the context to use keyed services and compare the two designs when the key comes from a query string.
  5. Write one unit test per strategy and one for the context using fake strategies.

πŸ’» Code

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

⚠ Common mistakes

  • Mistake: Injecting a single 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.
  • Mistake: Calling 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.
  • Mistake: Moving the 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.
  • Mistake: Storing per-request data in fields of a singleton strategy. Why it is wrong: Concurrent requests overwrite each other's state. Instead: Keep strategies stateless and pass data as arguments, or register them as scoped.
  • Mistake: Callers casting the interface back to a concrete strategy to call an extra method. Why it is wrong: The context now depends on concrete types and the pattern is defeated. Instead: Put what callers need on the interface, or split the interface.
  • Mistake: Turning a stable three-case 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.
  • Mistake: Throwing 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.

πŸ› Senior insight: trade-offs

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.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate says adding a variant no longer edits existing code Why: Checks Open/Closed applied pragmatically rather than as plug-in frameworks
    How to answer

    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.

  2. When: Candidate mentions passing a Func or lambda instead of an interface Why: Checks the built-in delegate types used as one-method strategies
    How to answer

    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.

  3. When: Candidate says the context delegates to a strategy it holds Why: Checks composition and delegation fundamentals behind Strategy
    How to answer

    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.

  4. When: Candidate says they would replace a switch with strategies Why: Checks applying Strategy as a safe, tested refactor
    How to answer

    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.

↩ Usually asked after

More in Behavioral Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me