C# Strategy Pattern

Summary: in this tutorial, you’ll learn about the C# strategy pattern that allows you to change the behavior of an object at runtime.

Introduction to the C# strategy pattern

The strategy design pattern allows you to choose an algorithm from a family of algorithms at runtime by encapsulating each algorithm in a class and making them interchangeable.

The strategy design pattern solves the problem of selecting one algorithm from a set of algorithms based on a condition, without tightly coupling the client code to the selected algorithm.

Suppose you have a program that performs an operation. But there are multiple ways to perform the same operation.

To do that, you can implement each algorithm as a separate method of a class. But that would make the code difficult to maintain and more complex if you want to add more algorithms. In other words, this design doesn’t conform to the open-closed principle.

The strategy pattern solves this problem by allowing you to encapsulate each algorithm in a separate class and make them interchangeable.

The strategy pattern is useful when you want to support different variants of an algorithm. And it is not practical to implement each algorithm as a separate method.

The strategy pattern is also useful when you want to select an algorithm at run time from a set of related algorithms.

Strategy pattern structure

The following UML diagram illustrates the strategy pattern:

The strategy pattern consists of three main elements:

  • Context: the class that holds a reference to the strategy object and is responsible for executing the algorithm.
  • Strategy: the interface that defines the methods which must be implemented by each concrete strategy.
  • Concrete Strategy: the classes that implement the strategy interface by providing their implementations of the algorithm.

In this structure, the context object holds a reference to a strategy object. When the context object needs to perform the algorithm, it delegates the task to the strategy object.

Benefits of the strategy pattern

  • The strategy pattern allows the client to select the algorithm to use at runtime.
  • The strategy pattern encapsulates each algorithm in a class, making it easy to modify and extend without affecting the other algorithms.
  • The strategy pattern decouples the algorithm from the client code, reducing coupling and promoting code reuse.

But strategy patterns can increase the complexity of the codebase by adding extra classes.

C# Strategy pattern implementation

The following example shows an implementation of the strategy pattern in C#:

namespace StrategyPattern;

// Strategy interface
public interface IStrategy
{
    void Execute();
}

// Concrete strategy A
public class ConcreteStrategyA : IStrategy
{
    public void Execute()
    {
        Console.WriteLine("Executing strategy A");
    }
}

// Concrete strategy B
public class ConcreteStrategyB : IStrategy
{
    public void Execute()
    {
        Console.WriteLine("Executing strategy B");
    }
}

// Context
public class Context
{
    private IStrategy? _strategy;

    public void SetStrategy(IStrategy strategy)
    {
        _strategy = strategy;
    }

    public void ExecuteStrategy()
    {
        _strategy?.Execute();
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var context = new Context();

        // Use the strategy A
        context.SetStrategy(new ConcreteStrategyA());
        context.ExecuteStrategy();

        // Use the strategy B
        context.SetStrategy(new ConcreteStrategyB());
        context.ExecuteStrategy();
    }
}Code language: C# (cs)

Known Uses of the Strategy Pattern in .NET

The strategy pattern is widely used in .NET, including:

  • The IComparer interface in the System.Collections namespace.
  • The SortedList class in the System.Collections.Specialized namespace.

Summary

  • The Strategy pattern enables clients to select a specific algorithm from a family of algorithms at runtime, without tightly coupling the client code to the selected algorithm.
Was this tutorial helpful ?