Friday, March 24, 2017

Fluent interface (API) in C#

Hi,

I was wondering why "fluent API" or "fluent interface" brings so many developer into trouble. I do like that kind of style, but I am not sure I would sacrifice my whole development style for this nice calling structure.

As a C# developer I found a way to go for me. I wrote an extension method on object-level like this:
1
2
3
4
5
6
7
8
    static class Fluent
    {
        public static T Do<T>(this T item, Action<T> method)
        {
            method(item);
            return item;
        }
    }

now i can work fluent like this:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
    class Program
    {
        static void Main(string[] args)
        {
            Console.Out
                .Do(x => x.WriteLine("test1"))
                .Do(x => x.WriteLine("test2"))
                .Do(x => x.WriteLine("test3"))
                .Do(x => x.WriteLine("test4"))
                .Do(x => x.WriteLine("test5"))
                .Do(x => x.WriteLine("test6"));
        }
    }

great.

It is probably not that expressive as it is in a real fluent interface, but it works for every single object in every single case...

Nevertheless see Martin Fowler's original post on FluentInterfaces: https://www.martinfowler.com/bliki/FluentInterface.html

kr,
Daniel

No comments: