Jul 15 2007

Fluent Interface in C#

Category:Bil@l @ 20:21

A nice post I passed through today: Fluent Interface.

It is a very nice programming style of adding "method-action" functionalities on an object. It makes you write less code and clear one! For instance, you can build Query-Like objects in an API using this style of fluent interface. Here is a sample code that shows how a C# object implements the fluent interface by adding "action-methods", where each method does a certain action "setting a value on an internal field" and return an instance of the object itself, here is the code:

public class CustomStringList
    List<string> innerList = null;

    public CustomStringList()
        this.innerList = new List<string>();

    public CustomStringList AddValue(string value)
        return this;

    public CustomStringList RemoveValue(string value)
        return this;

    public int Count
            return this.innerList.Count;

Now to use the above object, you can write something as:

        CustomStringList stringList =
            new CustomStringList()

        int numberOfElements= stringList.Count;

Hope you liked this post, as I am very impressed by this style and I have in mind so many ideas to build based on this fluent interface concept! You can read more on Fluent Interface here: http://en.wikipedia.org/wiki/Fluent_interface



Comments are closed