CreationalC#verifiedVerified

Builder Pattern in C#

Separates the construction of a complex object from its representation, allowing the same construction process to produce different results.

How to Implement the Builder Pattern in C#

1Step 1: Define the product

public class House
{
    public int Floors { get; set; }
    public bool HasGarage { get; set; }
    public bool HasPool { get; set; }
    public string? RoofType { get; set; }

    public override string ToString() =>
        $"House(Floors={Floors}, Garage={HasGarage}, " +
        $"Pool={HasPool}, Roof={RoofType})";
}

2Step 2: Builder with fluent interface

public class HouseBuilder
{
    private readonly House _house = new();

    public HouseBuilder SetFloors(int floors)
    {
        _house.Floors = floors;
        return this;
    }

    public HouseBuilder AddGarage()
    {
        _house.HasGarage = true;
        return this;
    }

    public HouseBuilder AddPool()
    {
        _house.HasPool = true;
        return this;
    }

    public HouseBuilder SetRoof(string roofType)
    {
        _house.RoofType = roofType;
        return this;
    }

3Step 3: Build returns the finished product

    public House Build() => _house;
}

// Usage:
// var house = new HouseBuilder()
//     .SetFloors(2)
//     .AddGarage()
//     .SetRoof("Gable")
//     .Build();

Builder Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Builder Pattern in the Real World

Consider ordering a custom sandwich at a deli. You tell the sandwich artist (builder) each step — bread type, protein, toppings, sauce — and they assemble it in the right order. You don’t need to know how to layer ingredients properly; you just specify what you want, and the builder hands you a finished sandwich.