Builder Pattern In C#

Problem

Initialize a new type using Builder Pattern in C#.

Solution

Create a simple immutable type.

  1. public sealed class Greeting  
  2. {  
  3.     private readonly string timeOfDay;  
  4.     private readonly string to;  
  5.   
  6.     public Greeting(string timeOfDay, string to)  
  7.     {  
  8.         if (string.IsNullOrEmpty(timeOfDay))  
  9.             throw new ArgumentException("Time of Day must be set");  
  10.   
  11.         if (string.IsNullOrEmpty(to))  
  12.             throw new ArgumentException("To must be set");  
  13.   
  14.         this.timeOfDay = timeOfDay;  
  15.         this.to = to;  
  16.     }  
  17.   
  18.     public string Message => $"Good {timeOfDay} {to}";  
  19. }  

Create a builder for this type.

Discussion

The idea behind an immutable type, as discussed in a previous post, is to create a class that once initialized, can’t be mutated (modified). For builder pattern to work, you don’t have to create an immutable type. However, I prefer to create value objects in the domain as immutable to simplify testing and avoid concurrency issues.

Method Chaining

The builder class has a method to set each ‘part’ of the type it will build. These methods return the builder itself in order to chain methods easily.

Notice that methods don’t return concrete builder; instead, they return an interface to indicate the ‘next’ step in the build process. The advantage of it is that developers using the class have IntelliSense to guide them during coding.

C#

Usage

The example above is trivial and the whole idea of using builder pattern may seem contrived. However, I’ve found this pattern useful when developing libraries that other developers will use in your team. It ensures that your services are set up correctly.

More interesting examples are within ASP.NET Core framework (e.g. WebHostBuilder) and a simple Azure library I wrote. The linked source code for this post also has an EmailBuilder, a bit more interesting example.

Source Code

GitHub


Similar Articles