This Article explains the Builder design pattern in C#, shows when to use it, and provides two working examples with code: a classic Builder (with Director) and a fluent-style Builder. Copy the code into your C# project and run to experiment.
What is the Builder Pattern?
The Builder pattern separates the construction of a complex object from its representation. It allows the same construction process to create different representations. It's useful when an object requires multiple steps to construct or when you want to create immutable objects with many optional parameters.
When to use
When the construction of an object is complex, it should be independent of the parts that make up the object.
When you want to create different representations of an object using the same construction process.
When an object has many optional parameters, Builder helps avoid telescoping constructors.
Benefits
Improved readability of client code (fluent builders).
Encapsulates construction logic in a single place.
Makes object creation expressive and less error-prone.
Example 1. Classic Builder with Director (House)
This example builds a House step-by-step. There is an IHouseBuilder interface, a ConcreteHouseBuilder, a Director that defines construction sequences, and the final House product.
// Product
public class House
{
public string Foundation { get; set; }
public string Structure { get; set; }
public string Roof { get; set; }
public string Interior { get; set; }
public override string ToString()
{
return $"House: Foundation={Foundation}, Structure={Structure}, Roof={Roof}, Interior={Interior}";
}
}
// Builder interface
public interface IHouseBuilder
{
void BuildFoundation();
void BuildStructure();
void BuildRoof();
void BuildInterior();
House GetHouse();
}
// Concrete builder
public class ConcreteHouseBuilder : IHouseBuilder
{
private House house = new House();
public void BuildFoundation()
{
house.Foundation = "Concrete and rebar";
}
public void BuildStructure()
{
house.Structure = "Brick and mortar";
}
public void BuildRoof()
{
house.Roof = "Tiles";
}
public void BuildInterior()
{
house.Interior = "Standard interior fit-out";
}
public House GetHouse()
{
var result = house;
house = new House(); // reset for next build
return result;
}
}
// Director
public class Director
{
private readonly IHouseBuilder builder;
public Director(IHouseBuilder builder)
{
builder = builder;
}
// Example: build a simple house
public void ConstructSimpleHouse()
{
builder.BuildFoundation();
builder.BuildStructure();
builder.BuildRoof();
_builder.BuildInterior();
}
}
// Usage
var builder = new ConcreteHouseBuilder();
var director = new Director(builder);
director.ConstructSimpleHouse();
House house = builder.GetHouse();
Console.WriteLine(house);

Join the conversation! Your thoughts help the community grow.