How to turn any api to a fluent API with extension methods in C#

Alex Reznick | November 22nd 2012 | Uncategorized

Let’s say you have a class A, which exposes an old fashion, not fluent api

public class A
{
    public A() {;// Code here}
    public void Add(Obj key, obj value) {;//code}
    public void DoSomething() {; //code}
}

In languages like Java, you would be stack with using this class in the old, and a very verbose way:

A a = new A();

a.Add("a", "b");
a.Add("c", "d");
a.Add("e", "f");
a.Add("g", "h");

a.DoSomething();

Another option would be implementing a Builder class that would provide the fluent API for you.
But with C# you can easily do it with just one extension method:

public static class AFluent
{
    public static With(this A a, object key, object value)
    {
        a.Add(key,value);
        return a;
    }
}

So the cumbersome code from before looks like:

new A()
    .With("a", "b")
    .With("c", "d")
    .With("e", "f")
    .With("g", "h")
    .DoSomething();

That’s it.


By Alex Reznick
Wix

Leave a Reply

We are always looking for excellent people. Browse Jobs Here   

At Wix Engineering we develop some of the most innovative cloud-based web applications that influence our 80+ million users worldwide.

Have any questions? Email academy@wix.com.

Find out what’s coming up at Wix Engineering:

Subscribe to our newsletter for updates, events and more.