Fluent Interface Design Pattern in C#

Fluent Interface Design Pattern in C# with Examples

In this article, I will discuss the Fluent Interface Design Pattern in C# with Examples. Please read our previous article discussing 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 will 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. Advantages of using Fluent Interface Design Pattern.
  5. When 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 is its implementation. 

What is the Fluent Interface Design Pattern?

The Fluent Interface Design Pattern in C# is a way of implementing object-oriented APIs in a manner that aims to provide more readable and discoverable code. It often involves method chaining, where each method returns the same context object, invoking multiple actions or commands in a single line of code. 

The core idea behind the Fluent Interface pattern is to make code more readable and to make the client code look like a domain-specific language. The Fluent Interface Design Pattern’s main objective is to apply multiple properties (or methods) to an object by connecting them with dots (.) without re-specifying 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, 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 it not nice to set the object properties as shown below?

How to Implement Fluent Interface Design Pattern in C#?

Creating such interfaces is like speaking a sentence that would make the class consumption code more simple and 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. To achieve this, first, we need to create a wrapper class around the Employee class, 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, the client code should look 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#. First, we need to create a class file named Employee.cs and then copy and paste the following code into it. This is a simple class having few properties. We aim 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:

To set the above Employee class Property Values using Method Chaining, we must create a Wrapper class around the Employee class. So, create a class file named FluentEmployee.cs and copy and paste the following code. This is going to be our Wrapper class. If you notice, here, we have created an instance of the Employee class. 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, which 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 them.

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 Program class is going to be the Client. So, from the Client, we need to create an instance of the FluentEmployee and 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. 

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#

Advantages of Fluent Interfaces:
  • Readability: Code is often more readable and expressive, resembling natural language, which makes it easier to understand.
  • Ease of Use: It guides the user through the process of configuring an object or system, making the API more discoverable and easier to use correctly.
  • Reduced Errors: By correctly guiding the developer through the necessary steps, fluent interfaces can reduce the risk of misconfiguration or errors.
  • Flexibility: Fluent interfaces can make refactoring or extending the underlying implementation easier without changing the external API.
  • Method Chaining: Returning the context object allows for concise and logical grouping of related actions on an object.
When to Use Fluent Interface Design Pattern in C#?

The Fluent Interface Design Pattern in C# is particularly beneficial in the following scenarios:

  • Building Complex Objects: When constructing complex objects, a fluent interface can make the process more intuitive and readable, especially when the object construction involves multiple steps or options.
  • Configuring Objects: It’s useful for configuring objects step-by-step, where each method call configures a specific aspect of the object, and the methods are chained together in a readable manner.
  • Creating API for DSL (Domain-Specific Language): Fluent interfaces are excellent for creating APIs that resemble a Domain-Specific Language, making the code more expressive and tailored to a specific domain or functionality.
  • Query Construction: Fluent interfaces are often used in building query languages, such as in ORMs (Object-Relational Mappers) like Entity Framework, where they allow for writing database queries in a way close to natural language.
  • Building Immutable Objects: They can be used effectively for building immutable objects, where each method call returns a new instance of the object with the modified state, maintaining immutability.
  • Method Chaining: In scenarios where method chaining improves code clarity and conciseness. This is common in configuration settings, builder patterns, or initialization processes.
  • Enhancing Readability and Flow: When you want to improve the readability and flow of the code. Fluent interfaces often make the code look more like a series of natural language statements, which can be easier to understand and maintain.

In the next article, I will discuss the Real-Time Examples of the Fluent Interface Design Pattern in C#. In this article, I try to explain the Fluent Interface Design Pattern in C# with Examples. I hope you understand the need for and use of the Fluent Interface Design Pattern.

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

  1. Hi. There is a problem here: the fluent interface doesn’t return the object, thus making it a bit useless. 🙂

Leave a Reply

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