Prab's Code Blog

Because talk is cheap, show me the code!

Here's a Fluent Builder in C#

A fluent builder makes creating objects more readable than constructors and more concise than setting properties through setters on an uninitialized object. Java devs can use Lombok’s @Builder annotation to get a fluent builder wired into their classes. Unfortunately, in C# world no such thing exists. So here’s how you can roll out your own.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Animal
{
  public string Name { get; set; }

  public string Type { get; set; }


  #region Fluent builder
  public static Animal Builder()
  {
    return new Animal();
  }

  public Animal WithName(string name)
  {
    this.Name = name;
    return this;
  }

  public Animal WithType(string type)
  {
    this.Type = type;
    return this;
  }

  public Animal Build()
  {
    return this;
  }
  #endregion
}

And, to construct and object you can simply use:

1
Animal a = Animal.Builder().WithName("Tommy").WithType("Dog").Build();

Update

C# doesn’t need this. I figured it out after reading and writing lot of C# code. C# already has a nice intializer which can be used instead of a fluent builder:

1
2
3
4
5
Animal a = new Animal
{
    Name = "Tommy",
    Type = "Dog"
};

Comments