How would you implement the Builder pattern using method chaining (a fluent API) to construct a complex object step by step?
Short answer
Define a builder class with methods that each set part of the object being built and RETURN 'this' (the builder itself), enabling method chaining; a final Build() method assembles and returns the fully-configured object — useful when an object has many optional configuration…
Advertisement
AModel answer
Define a builder class with methods that each set part of the object being built and RETURN 'this' (the builder itself), enabling method chaining; a final Build() method assembles and returns the fully-configured object — useful when an object has many optional configuration parameters that would otherwise require an unwieldy constructor with many arguments.
public class EmailBuilder {
private readonly Email _email = new();
public EmailBuilder To(string address) { _email.To = address; return this; }
public EmailBuilder Subject(string subject) { _email.Subject = subject; return this; }
public Email Build() => _email;
}
var email = new EmailBuilder().To("sam@x.com").Subject("Hello").Build();Real-world example
Constructing a complex configuration object (like an HTTP request or an email message) with many optional parameters readably.
Likely follow-ups
- How do C# 12's collection expressions or object initializer syntax sometimes reduce the NEED for a full Builder pattern for simpler cases?
Related topics