The concept of Fluent Interface was coined by Martin Fowler to create various objects and wire them up together. This pattern is often used for object configuration and setup. For example in ASP.NET Core applications we have following code for configuring the server:
As you can see we can chain methods together easily and the intention is to produce an API that is readable and flows. This pattern is heavily used in programming, Here’s an example of using this approach in jQuery:
For C#, there is LINQ:
You might ask how to implement this pattern, well, it is very simple you just need to return this during method call. The Calculator defined below contains three methods. These methods are returing Calculator object using this keyword, which allow to chain the methods:
Now we can use the class this way:
As you can see this approach makes our code concise and easier to read.