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) { ProcessValue(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(); builder.AddValue(...) .AddValue(...) .If(condition, b => b.AddValue(...)) .AddValue(...);
Other approaches are presented as SO answers like here and here.
Thanks for sharing
I’ve a problem in using IF extension, can you help me https://stackoverflow.com/questions/75017535/c-sharp-how-to-make-a-conditional-method-chaining-in-fluent-interface