← All topics
🧩 Design Patterns

Builder Pattern

Step-by-step construction of complex objects, fluent APIs.

Builder separates the construction of a complex object from its representation, usually via a fluent, chainable API — most useful when an object has many optional parameters/configuration steps and a giant constructor (or worse, multiple overloaded constructors) would be unreadable.

You've almost certainly already used this: HostBuilder/WebApplicationBuilder in ASP.NET Core, DbContextOptionsBuilder, and StringBuilder are all Builder pattern instances — a good real-world anchor if asked "where have you seen this before."

public class HttpRequestMessageBuilder
{
    private readonly HttpRequestMessage _request = new();
    public HttpRequestMessageBuilder WithUrl(string url) { _request.RequestUri = new Uri(url); return this; }
    public HttpRequestMessageBuilder WithMethod(HttpMethod method) { _request.Method = method; return this; }
    public HttpRequestMessageBuilder WithHeader(string key, string value) { _request.Headers.Add(key, value); return this; }
    public HttpRequestMessage Build() => _request;
}

Flashcards (2)

What problem does the Builder pattern solve, specifically?
tap to reveal answer
Constructing complex objects with many optional parameters/configuration steps, without needing a huge constructor or a combinatorial explosion of constructor overloads — usually via a fluent, chainable API.
Name two Builder-pattern examples you've already used in ASP.NET Core / .NET without necessarily calling it that.
tap to reveal answer
WebApplicationBuilder (builder.Services.Add..., builder.Build()), DbContextOptionsBuilder, and StringBuilder are all Builder pattern implementations.