Builder Pattern in C#

Problem

Initialise a new type using Builder pattern in C#

Solution

Create a simple immutable type:

Create a builder for this type:

The builder can be used like:

Discussion

The idea behind an immutable type, as discussed in a previous post, is to create a class that once initialised 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 is that developer using the class has IntelliSense to guide them during coding:

Builder Pattern - Usage

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 setup 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: https://github.com/TahirNaushad/Fiver.Design.Builder

4 comments

  1. Greaaat job, Tahir. This is excellent!

    I am trying to do a GET request on a secure API endpoint. In the HttpRequestFactory class, I overloaded the “Get” method as follow:

    public static async Task Get(string requestUri, string bearerToken)
    {
    var builder = new HttpRequestBuilder()
    .AddMethod(HttpMethod.Get)
    .AddRequestUri(requestUri)
    .AddBearerToken(bearerToken);

    return await builder.SendAsync();
    }

    However, I am getting the following exception:

    “Invalid URI: The URI scheme is not valid.”

    I know I must be missing something obvious, but I can’t figure out that it is, yet.

    Thanks for your help.

Leave a Reply