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.
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.
"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, andBuild()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.
StringBuilderassembles a string in a mutable buffer andToString()is the build step.SqlConnectionStringBuilderandUriBuilderavoid string concatenation bugs.DbContextOptionsBuilderand Polly'sResiliencePipelineBuilderconfigure complex options. The one everyone knows isWebApplication.CreateBuilder(args), orHost.CreateApplicationBuilder(args)for workers. You configurebuilder.Services,builder.Configurationandbuilder.Logging, thenBuild()creates theWebApplication. 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,
requiredplusinitwith 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."
| 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() |
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 |
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.
Checks that the candidate understands Builder's intent (staged construction with validation) and knows modern C# alternatives.
Green flags
Build().WebApplicationBuilder and its frozen service collection.required/init is enough.Red flags
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.
WithX method mutates private state and returns this.Build() validates and creates the product, ideally an immutable record.internal or private so only the builder can create it.Variations:
WithX returns a new builder (records with with make this easy). It's safe to share partial configurations.ForCustomer(...) returns INeedsItems), giving compile-time guidance at the cost of many interfaces.WebApplicationBuilder worksWebApplication.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.
StringBuilder as a builderIt 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.
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.
required, init and withrequired (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().
OrderBuilder for tests and convert five tests that use constructors.builder.Build() in a minimal API and read the exception.SqlConnectionStringBuilder and try a password containing ;.string += vs StringBuilder for 10,000 appends with BenchmarkDotNet [MemoryDiagnoser].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
required/init and object initialisers unless there are cross-field rules or steps.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.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().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().;, = or ? break parsing or open injection holes. Instead: SqlConnectionStringBuilder, UriBuilder, QueryHelpers.AddQueryString.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.
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.
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.
Last updated 18 Nov 2026.