Fluent Interface Design Pattern in C# with Examples


In this article, we will talk about the Fluent Interface Design Pattern in C# with examples. The Fluent Interface Design Pattern is a type of Creational Design Pattern.

Fluent Interface Design Pattern

The purpose of a fluent design pattern is to use multiple properties for the objects by connecting them with the .(dot) without giving the specifics of the object again.

A fluent interface design pattern is implemented by using the method cascading or concrete method chaining.

Implementation of Fluent Interface Design Pattern in C#
let's create a student class

public class Student
{

    public string Name { get; set; }

    public int Age { get; set; }

    public string Address { get; set; }

}

now let's assign values to student class

Student emp = new Student()
{

    Name  = "DotNet office",

    Age  = 12,

    Address  = "India"

};


What is Method Chaining?

Method chaining is the technique where each method returns an object and all of these methods can be chained together to create a single statement. to implement this, first, we need to create the wrapper class around the student class.

 public class StudentFluentExample


    {

        private Student obj = new Student();

        public StudentFluentExample NameOfTheStudent(string name)

        {

          obj.Name = name;

            return;

        }

        public StudentFluentExample Age(int age)

        {

            obj.Age = age;

            return;

        }

        public StudentFluentExample LivesIn(string address)

        {

            obj.Address = address;

            return;

        }

       

    }

now to access the above class methods we have to create an object of the class like below

as per fluent interfaces design pattern, we can access properties by connecting them with .(dot) like below
static void Main(string[] args)

        {
          StudentFluentExample obj = new StudentFluentExample();
          obj.NameOfTheStudent("Dotnet office").Age(12).LivesIn("India");

        }

uses of the Fluent Interface Design Pattern in C#
  1. Fluent code is more readable and allows us to vary a product's internal representation
  2. A fluent design pattern encapsulates the code for construction and representation and it Provides control over the steps of the object construction process.
  3. Sorting, Searching, and pagination using LINQ are some of the real-world examples of the fluent interface in the combination with the builder design pattern.


Share this

Related Posts

Previous
Next Post »