Conditions in Fluent Interface Method Chaining

In one of my projects, I created a builder library for a set of classes with many parent-child relations. I wrote the builder classes such that the parameters and child objects could be defined by method chaining, which is also used in Fluent interfaces.

When implementing method chaining, a method is declared as returning the object it is executing on:

public class Builder {
  public Builder AddValue(object value) {
    return this;

As work progressed, some of the objects to be built showed minor differences, and I thought about how to add chained methods conditionally.

Finally, the solution I came up with looks like this:

public static class BuilderExtensions {
  public static T If<T>(this T t, bool cond, Func<T, T> builder)  
    where T : Builder
    if (cond)
      return builder(t);
    return t;

This extension method allows for inline conditions such as

var builder = new Builder();
  .If(condition, b => b.AddValue(...))

Other approaches are presented as SO answers like here and here.

1 thought on “Conditions in Fluent Interface Method Chaining

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.