📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the Builder pattern? Explain fluent builders, how WebApplicationBuilder and HostApplicationBuilder use it, test data builders, and when C# required and init properties with an object initialiser are enough instead.

GoF Builder vs fluent builder, framework builders (StringBuilder, UriBuilder, SqlConnectionStringBuilder, WebApplicationBuilder, HostApplicationBuilder, DbContextOptionsBuilder, ResiliencePipelineBuilder), test data builders, validation in Build(), and when required/init initialisers replace a builder.

Intermediate Theory Intermediate aspnet-core builder csharp design-patterns fluent-api testing

🎯 Key points

  • Builder separates step-by-step construction of a complex object from its representation; the product is created only in Build()
  • Fluent builder: methods return the builder (this) so calls chain; Build() validates cross-field rules and returns an immutable product
  • WebApplication.CreateBuilder(args) / Host.CreateApplicationBuilder(args): configure Services, Configuration, Logging, then Build(); services are frozen after Build()
  • Other .NET builders: StringBuilder, UriBuilder, SqlConnectionStringBuilder, DbContextOptionsBuilder, ResiliencePipelineBuilder, ImmutableArray<T>.Builder
  • Test data builders supply valid defaults so each test states only what matters (new OrderBuilder().WithStatus(Shipped).Build())
  • Builder replaces telescoping constructors (many overloads with optional parameters) where order of arguments is error-prone
  • required (C# 11) + init + object initialisers are enough when there are no cross-field invariants or multi-step construction; they give compile-time errors, Build() validation gives run-time errors
  • Cost: an extra mutable type mirroring the product, and builders reused after Build() can leak state between products unless Build() copies

⏱ 30-second answer

Builder builds a complex object step by step and creates it only in Build(), so callers never see a half-built object. Most C# builders are fluent: each method returns the builder so calls chain, and Build() checks cross-field rules before returning an (often immutable) product.

.NET is full of builders: StringBuilder, UriBuilder, SqlConnectionStringBuilder, DbContextOptionsBuilder, ResiliencePipelineBuilder and WebApplication.CreateBuilder(args). With that last one you configure Services and Configuration, call Build(), and the service collection is then frozen. In tests, test data builders give valid defaults so each test sets only what it cares about.

If an object has no cross-field rules, required/init properties with an object initialiser are simpler. A builder is an extra type to maintain.

🗣 Full answer (senior)

How I would answer this in an interview

"Builder is for objects that are awkward to create in one go: lots of optional parts, rules that span several fields, or a result that should be immutable but is easiest to assemble in steps. The builder collects the parts, and only Build() creates the product. That means nobody ever holds a half-configured object, and Build() is the single place to validate. The GoF version has a Director driving an abstract Builder. In C# we mostly write fluent builders, where each method returns the builder so calls chain.

The framework is full of them. StringBuilder assembles a string in a mutable buffer and ToString() is the build step. SqlConnectionStringBuilder and UriBuilder avoid string concatenation bugs. DbContextOptionsBuilder and Polly's ResiliencePipelineBuilder configure complex options. The one everyone knows is WebApplication.CreateBuilder(args), or Host.CreateApplicationBuilder(args) for workers. You configure builder.Services, builder.Configuration and builder.Logging, then Build() creates the WebApplication. After that the service collection is read-only, which is exactly the Builder guarantee. In tests I use test data builders: new OrderBuilder().WithStatus(OrderStatus.Shipped).Build(), which supplies valid defaults for everything else. Each test then reads as its intent, and adding a required field changes one builder instead of 200 tests.

The mistake I see is writing a builder for a DTO with six independent properties. Since C# 11, required plus init with an object initialiser gives compile-time enforcement of mandatory fields and immutability after construction, with no extra class. I reach for a builder when construction has rules or steps, not just many properties."


Builders in .NET

Builder Product Build step
StringBuilder string ToString()
UriBuilder Uri .Uri
SqlConnectionStringBuilder connection string .ConnectionString
WebApplicationBuilder WebApplication Build()
HostApplicationBuilder IHost Build()
DbContextOptionsBuilder<T> DbContextOptions<T> .Options
ResiliencePipelineBuilder ResiliencePipeline Build()
ImmutableArray<T>.Builder ImmutableArray<T> ToImmutable() / MoveToImmutable()

Builder vs required/init

Situation Use
A few mandatory properties, no cross-field rules required + init + object initialiser
Many optional parts with defaults Builder or with on a default instance
Rules across fields ("end after start", "either email or phone") Builder that validates in Build(), or a constructor/factory method
Multi-step assembly (add lines, then totals) Builder
Test setup with mostly default values Test data builder

Production example

In a test suite with about 1,800 tests, adding a mandatory TaxRegion field to Order broke over 600 tests that called the constructor directly. After moving to an OrderBuilder with valid Australian defaults (GST region, AUD currency), the next new mandatory field changed one line in the builder and no tests.

🔍 What the interviewer is checking

Checks that the candidate understands Builder's intent (staged construction with validation) and knows modern C# alternatives.

Green flags

  • Explains why the product is created only in Build().
  • Names framework builders, especially WebApplicationBuilder and its frozen service collection.
  • Uses test data builders and explains the maintenance benefit.
  • Knows when required/init is enough.

Red flags

  • Builders for every class.
  • Can't distinguish a builder from a factory.
  • Validation scattered across setter methods.

📚 Learn in depth

1. GoF structure

Director ──uses──▶ «interface» IBuilder
  Construct()          + BuildPartA()
                       + BuildPartB()
                       + GetResult(): Product
                             ▲
                      ConcreteBuilder ──creates──▶ Product

The Director knows the order of steps; the builder knows how to build each part. In C# the Director is usually just the calling code, and the abstract builder interface is rarely needed. What survives is the fluent concrete builder.

2. Fluent builder mechanics

  • Each WithX method mutates private state and returns this.
  • Build() validates and creates the product, ideally an immutable record.
  • The product's constructor can be internal or private so only the builder can create it.

Variations:

  • Immutable builder: each WithX returns a new builder (records with with make this easy). It's safe to share partial configurations.
  • Step builder: interfaces force the order (ForCustomer(...) returns INeedsItems), giving compile-time guidance at the cost of many interfaces.

3. How WebApplicationBuilder works

WebApplication.CreateBuilder(args) creates a ConfigurationManager (sources: appsettings, environment, user secrets in Development, command line), a ServiceCollection, a logging builder and the host environment. You add services and configuration. Build() builds the ServiceProvider, applies ValidateScopes/ValidateOnBuild in Development, and marks the IServiceCollection read-only; adding a service afterwards throws InvalidOperationException. HostApplicationBuilder (.NET 7+) is the same linear model for worker services, replacing the older callback-based IHostBuilder.ConfigureServices(...) style.

4. StringBuilder as a builder

It keeps a linked list of char[] chunks, so appends are amortised O(1) without copying the whole string. ToString() allocates the final string once. That's the Builder idea applied to performance: a mutable assembly phase, then one immutable product.

5. Test data builders

The pattern (from Growing Object-Oriented Software, Guided by Tests) gives every field a valid default, so a test only states what matters:

var order = new OrderBuilder().WithStatus(OrderStatus.Cancelled).Build();

Benefits: tests express intent, and adding a required field changes one place. Libraries like Bogus or AutoFixture generate random data instead. That's good for broad coverage, but less readable when one value matters.

6. required, init and with

  • required (C# 11): the compiler errors if an object initialiser doesn't set the member (unless the constructor has [SetsRequiredMembers]).
  • init: settable only during initialisation, immutable afterwards.
  • with on records: copy-and-modify from a default instance, a lightweight builder alternative (DefaultOptions with { Timeout = 5s }).

None of these validates cross-field rules. For that you need a constructor, a factory method or a builder's Build().

Try it yourself

  1. Write an OrderBuilder for tests and convert five tests that use constructors.
  2. Try to add a service after builder.Build() in a minimal API and read the exception.
  3. Replace string concatenation of a connection string with SqlConnectionStringBuilder and try a password containing ;.
  4. Benchmark string += vs StringBuilder for 10,000 appends with BenchmarkDotNet [MemoryDiagnoser].

💻 Code

A fluent builder with validation, a test data builder, and the required/init alternative:

namespace Notifications;

public sealed record EmailMessage(string To, string Subject, string Body, IReadOnlyList<string> Cc, DateTimeOffset? SendAt);

// Fluent builder: cross-field rules checked once, in Build()
public sealed class EmailMessageBuilder
{
    private string? _to;
    private string _subject = "";
    private string _body = "";
    private readonly List<string> _cc = [];
    private DateTimeOffset? _sendAt;

    public EmailMessageBuilder To(string address) { _to = address; return this; }
    public EmailMessageBuilder Subject(string subject) { _subject = subject; return this; }
    public EmailMessageBuilder Body(string body) { _body = body; return this; }
    public EmailMessageBuilder Cc(string address) { _cc.Add(address); return this; }
    public EmailMessageBuilder SendAt(DateTimeOffset when) { _sendAt = when; return this; }

    public EmailMessage Build(TimeProvider time)
    {
        if (string.IsNullOrWhiteSpace(_to)) throw new InvalidOperationException("A recipient is required.");
        if (_subject.Length == 0 && _body.Length == 0) throw new InvalidOperationException("Subject or body is required.");
        if (_sendAt is { } at && at < time.GetUtcNow()) throw new InvalidOperationException("SendAt must be in the future.");
        return new EmailMessage(_to, _subject, _body, _cc.ToArray(), _sendAt);   // copy: builder reuse can't mutate the product
    }
}
// Test data builder: valid defaults, tests set only what matters
namespace Orders.Tests;

public sealed class OrderBuilder
{
    private OrderStatus _status = OrderStatus.Placed;
    private string _currency = "AUD";
    private readonly List<OrderLine> _lines = [new("SKU-1", 1, 10m)];

    public OrderBuilder WithStatus(OrderStatus status) { _status = status; return this; }
    public OrderBuilder WithLine(string sku, int qty, decimal price) { _lines.Add(new(sku, qty, price)); return this; }
    public Order Build() => new(Guid.NewGuid(), _status, _currency, [.. _lines]);
}

// [Fact] public void Cancelled_orders_cannot_ship() =>
//     Assert.Throws<InvalidOperationException>(() => new OrderBuilder().WithStatus(OrderStatus.Cancelled).Build().Ship());
// When no cross-field rules exist, required + init is enough
namespace Notifications;

public sealed record SmsMessage
{
    public required string To { get; init; }
    public required string Text { get; init; }
    public string? SenderId { get; init; }
}

// var sms = new SmsMessage { To = "+61400000000", Text = "Your order shipped" };   // compiler enforces To and Text

⚠ Common mistakes

  • Mistake: Writing a builder for every DTO. Why it is wrong: A second class mirroring every property doubles maintenance for no added safety. Instead: Use required/init and object initialisers unless there are cross-field rules or steps.
  • Mistake: Build() returning the builder's internal list. Why it is wrong: Reusing the builder mutates products that were already built. Instead: Copy collections in Build() and return immutable types.
  • Mistake: Putting validation in each WithX method. Why it is wrong: Cross-field rules can't be checked until all parts are set, and order of calls becomes significant. Instead: Validate in Build().
  • Mistake: Trying to add services after builder.Build(). Why it is wrong: The service collection is read-only after building; it throws InvalidOperationException. Instead: Register everything on builder.Services before Build().
  • Mistake: Test data builders with random or invalid defaults. Why it is wrong: Tests become flaky or fail for reasons unrelated to what they test. Instead: Deterministic, valid defaults; let tests override only what matters.
  • Mistake: Concatenating connection strings or URLs by hand. Why it is wrong: Values containing ;, = or ? break parsing or open injection holes. Instead: SqlConnectionStringBuilder, UriBuilder, QueryHelpers.AddQueryString.
  • Mistake: Sharing one mutable builder across threads or tests. Why it is wrong: Builders are mutable by design; concurrent use corrupts state. Instead: Create a builder per use, or make it immutable.

🏛 Senior insight: trade-offs

Builder earns its place when construction has rules or stages. Modern C# removed most of the "many constructor parameters" motivation: required, init, records and with handle that more cheaply. Where Builder still wins is test data, complex configuration APIs, and assembling immutable aggregates in steps.

Option When it fits Cost When not to
Constructor Few mandatory values, invariants Long parameter lists get unreadable Many optional parts
required + init initialiser Independent properties, mandatory fields No cross-field validation Rules across fields
Record + with from defaults Options objects with sensible defaults Shallow copy Deep nested mutable parts
Fluent builder Cross-field validation, staged assembly, readable config APIs Extra mutable type Simple DTOs
Test data builder Test setup One class per aggregate Production code paths

In library or framework APIs, I prefer builders that end in a frozen product, like WebApplicationBuilder, because the freeze makes misuse fail loudly instead of silently ignoring late configuration.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says required and init replace many builders Why: Checks constructors, primary constructors and required members
    How to answer

    A constructor runs when an object is created and should leave it valid. If you declare none, the compiler adds a public parameterless one. Constructors can chain: : this(...) calls another constructor of the same class, : base(...) calls the base class's. For new Derived(), the order is: derived field initialisers, base field initialisers, base constructor body, derived constructor body. A static constructor runs once, before the type is first used, and is thread-safe. Primary constructors (C# 12) put parameters on the class declaration; they are captured as hidden fields, not properties, and are mutable. required members (C# 11) force callers to set them in an object initialiser. Calling a virtual method from a constructor runs the derived override before the derived constructor body has run, so it can see uninitialised state.

  2. When: Candidate says Build() returns an immutable object Why: Checks immutability trade-offs for the built product
    How to answer

    Prefer immutable types for values, messages, configuration, cache entries and anything shared across threads: an object that cannot change is automatically thread-safe, safe to cache and share, safe as a dictionary key, and easier to reason about. C# gives you readonly fields, init and get-only properties, records with with, readonly struct, ImmutableArray<T>/ImmutableList<T> and FrozenDictionary/FrozenSet for read-mostly data. Remember that read-only is not immutable: IReadOnlyList<T> over a List<T> can still change underneath. Keep mutability where it is natural and contained: entities whose state changes through methods that guard invariants, builders, and hot loops where allocating new objects would cost too much.

More in Creational Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me