Search code examples
c#fluent-interface

Why use a Fluent Interface?


When comparing to classic properties, what's the big gain of using it ?

I know the repeating of the instance name is gone, but that's all ?

public class PropClass
{
  public Object1 object1 { get; set; }
  public Object2 object2 { get; set; }
}

PropClass propClass = new PropClass();
propClass.object1 = o1;
propClass.object2 = o2;

public class FluentClass
{
    public Object1 object1 { get; private set; }
    public Object2 object2 { get; private set; }

    public FluentClass SetObject1(Object1 o1)
    {
        object1 = o1;
        return this;
    }

    public FluentClass SetObject2(Object1 o2)
    {
        object1 = o2;
        return this;
    }
}

FluentClass fluentClass = new FluentClass().SetObject1(o1).SetObject1(o2);

Solution

  • IMHO there's no big gain of setting properties with fluent interface, especially with C# 3.0 class initializers. Fluent interfaces become more interesting when you start chaining methods and operations.