Fluent Interface Design Pattern in C#

Fluent Interface Design Pattern in C# with Examples

In this article, I am going to discuss the Fluent Interface Design Pattern in C# with Examples. Please read our previous article where we discussed the Builder Design Pattern in C# with Examples. The Fluent Interface Design Pattern falls under the category of the Creational Design Pattern. As part of this article, we are going to discuss the following pointers.

  1. What is the Fluent Interface Design Pattern?
  2. Understanding Method Chaining in C#.
  3. Implementing Fluent Interface Design Pattern in C#.
  4. When do we need to use the Fluent Interface Design Pattern?

Note: The Fluent Interfaces and Method Chaining are related to each other. Or we can say that one is a concept and the other one is its implementation. Here in this article, first, we will discuss fluent interfaces and then we will move towards method chaining.

What is the Fluent Interface Design Pattern?

The main objective of the Fluent Interface Design Pattern is that we can apply multiple properties (or methods) to an object by connecting them with dots (.) without having to re-specify the object name each time.

How to Implement Fluent Interface Design Pattern in C#?

Let us understand How to Implement the Fluent Interface Design Pattern in C# with an Example. Let’s say, we have the following Employee class.

What is the Fluent Interface Design Pattern?

If we want to consume the above Employee class, then we generally, create an instance of the Employee class and set the respective properties as shown below.

Without Fluent Interface in C#

The Fluent interfaces simplify our object consumption code by making our code more simple, readable, and discoverable. Is not it nice to set the object properties as shown below?

How to Implement Fluent Interface Design Pattern in C#?

If we create such kinds of interfaces, then it is like speaking a sentence that would really make the class consumption code more simple and more readable. Now the next thing is how to achieve this. To achieve this, we have something called Method Chaining in C#.

What is Method Chaining in C#?

Method Chaining in C# is a common technique where each method returns an object and all these methods can be chained together to form a single statement. In order to achieve this, first, we need to create a wrapper class around the Employee class something as shown below.

Fluent Interface Design Pattern in C# with Examples

As you can see, here we have created methods for each property. Also, notice the return of the method is set to the FluentEmployee. Now the above fluent interface is going to be consumed by the client. So, with the above FluentEmployee class in place, now the client code should look something as shown below.

What is Method Chaining in C#?

Example to Implement Fluent Interface Design Pattern using C#

Whatever we have discussed so far, let us implement the same using the Fluent Interface Design Pattern in C#. Let us first create a class file with the name Employee.cs and then copy and paste the following code into it. This is a simple class having few properties. And our aim is to set these property values using Method Chaining.

using System;
namespace FluentInterfaceDesignPattern
{
    public class Employee
    {
        public string FullName { get; set; }
        public DateTime DateOfBirth { get; set; }
        public string Department { get; set; }
        public string Address { get; set; }
    }
}
Creating Wrapper:

In order to set the above Employee class Property Values using Method Chaining, we need to create a Wrapper class around the Employee class. So, create a class file with the name FluentEmployee.cs and then copy and paste the following code into it. This is going to be our Wrapper class. If you notice, here, we have created an instance of the Employee class and for each Employee class property, here we have created a corresponding method and using those methods we are setting the Employee object property values. Further, if you notice, the return type of each method (except ShowDetails) is FluentEmployee type and this is important. Because of this return type (which is returning the FluentEmployee instance), we can call the FluentEmployee class methods (except ShowDetails) one after another using the dot operator. The ShowDetails method is not for setting the values, it is used to display the values.

using System;
namespace FluentInterfaceDesignPattern
{
    public class FluentEmployee
    {
        private Employee employee = new Employee();
        public FluentEmployee NameOfTheEmployee(string FullName)
        {
            employee.FullName = FullName;
            return this;
        }
        public FluentEmployee Born(string DateOfBirth)
        {
            employee.DateOfBirth = Convert.ToDateTime(DateOfBirth);
            return this;
        }
        public FluentEmployee WorkingOn(string Department)
        {
            employee.Department = Department;
            return this;
        }
        public FluentEmployee StaysAt(string Address)
        {
            employee.Address = Address;
            return this;
        }
        public void ShowDetails()
        {
            Console.WriteLine($"Name: {employee.FullName}, \nDateOfBirth: {employee.DateOfBirth}, \nDepartment: {employee.Department}, \nAddress: {employee.Address}");
        }
    }
}
Using Wrapper in the Client Code:

In our example, the Main method of the Program class is going to be the Client. So, from the Client, we need to create an instance of the FluentEmployee and we need to call the FluentEmployee class methods one after another using the dot (.) operator which is nothing but Method Chaining. So, modify the Main method of the Program class as follows. The following example code is self-explained, so please go through the comment lines for a better understanding.

using System;
namespace FluentInterfaceDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create an Instance of Wrapper class i.e. FluentEmployee
            FluentEmployee obj = new FluentEmployee();

            //Call Methods one by one using dot Operator whose Return Type is FluentEmployee
            obj.NameOfTheEmployee("Anurag Mohanty")
                    .Born("10/10/1992")
                    .WorkingOn("IT")
                    .StaysAt("Mumbai-India");

            //To See the Details call the ShowDetails Method
            obj.ShowDetails();
            Console.Read();
        }
    }
}
Output:

When do we need to use the Fluent Interface Design Pattern in C#

When do we need to use the Fluent Interface Design Pattern in C#?
  1. During UNIT testing when the developers are not full-fledged programmers.
  2. When you want your code to be readable by non-programmers so that they can understand whether the code is satisfied with their business logic or not.
  3. If you are a component seller and you want to stand out in the market as compared to the others by making your interface simpler.

I have seen fluent interfaces used extensively in LINQ Queries: Searching, Sorting, Pagination, and Grouping with a blend of LINQ are some of the real-world usages of the fluent interface.

In the next article, I am going to discuss the Prototype Design Pattern in C# with Examples. Here, in this article, I try to explain the Fluent Interface Design Pattern in C# with Examples. I hope you understood the need for and use of the Fluent Interface Design Pattern.

1 thought on “Fluent Interface Design Pattern in C#”

Leave a Reply

Your email address will not be published. Required fields are marked *