DESIGN PATTERNS SERIES

How to Switch the Algorithms at Runtime with Strategy Pattern in C#

When, Why, and How to use Strategy Pattern in C#. The quick and easy introduction.

Daniel Rusnok
.NET Core
Published in
5 min readJun 5, 2020

--

Four switch button
Source

The Strategy Pattern

Strategy Pattern or SP enables selecting an algorithm at runtime. Simply said, we choose an algorithm based on the incoming dynamic parameter.

Sounds like decision-statement, right? Switching an algorithm based on parameter value? We are talking about a switch or if-else statements, correct?

Well, yes. SP is some kind of decision-statement. But SP follows rules of Object-oriented programming languages and brings theirs advantages to the table like reusability and extensibility. It also meets the requirements of the SOLID code.

Advantages of the Strategy Pattern

  • It’s easy to switch between different algorithms (strategies) in runtime because you’re using polymorphism in the interfaces.
  • Clean code because you avoid decision-statements (not complicated).
  • More clean code because you separate the concerns into classes (a class to each Strategy).
  • Decoupled and easily testable code.

--

--

Daniel Rusnok
.NET Core

Senior Software Developer. Loving to gain & share knowledge. Focused on Microsoft technologies like Azure, .NET Core & C#. Software Architecture enthusiasist.