3/26/2026

Builder Pattern

Builder Pattern in C#

The Builder Pattern helps construct complex objects step-by-step. It is useful when you want to prevent creating incomplete or invalid objects. For example, just like a car should not be created without a steering wheel, your object should not be created without required fields.


Without Builder Pattern

When many parameters are required, constructors become difficult to maintain and easy to misuse.


public class User
{
    public string Name { get; }
    public int Age { get; }
    public string Email { get; }
    public string Address { get; }

    public User(string name, int age, string email, string address)
    {
        Name = name;
        Age = age;
        Email = email;
        Address = address;
    }
}

// Hard to remember parameter order
var user = new User("Vinodh", 30, "v@example.com", "Bangalore");

With Builder Pattern (With Validation)

The Builder Pattern allows you to set values step-by-step and validate them before creating the final object.


public class User
{
    public string Name { get; private set; }
    public int Age { get; private set; }
    public string Email { get; private set; }
    public string Address { get; private set; }

    private User() { }

    public class Builder
    {
        private readonly User _user = new User();

        public Builder SetName(string name)
        {
            _user.Name = name;
            return this;
        }

        public Builder SetAge(int age)
        {
            _user.Age = age;
            return this;
        }

        public Builder SetEmail(string email)
        {
            _user.Email = email;
            return this;
        }

        public Builder SetAddress(string address)
        {
            _user.Address = address;
            return this;
        }

        public User Build()
        {
            // Validation logic – prevents invalid object creation
            if (string.IsNullOrWhiteSpace(_user.Name))
                throw new Exception("Name is required.");

            if (_user.Age <= 0)
                throw new Exception("Age must be a positive value.");

            if (string.IsNullOrWhiteSpace(_user.Email))
                throw new Exception("Email is required.");

            // Similar to: a car cannot be created without a steering wheel
            if (string.IsNullOrWhiteSpace(_user.Address))
                throw new Exception("Address cannot be empty.");

            return _user;
        }
    }
}

Usage


var user = new User.Builder()
    .SetName("Vinodh")
    .SetAge(30)
    .SetEmail("v@example.com")
    .SetAddress("Bangalore")
    .Build();

Conclusion

The Builder Pattern prevents invalid object creation through step-by-step construction and validation. Just like a car must not be built without vital parts, your objects remain consistent and safe.

No comments:

Post a Comment