Fluent Interface Pattern in under 5 Minutes With C#

Publish date: Jun 19, 2019
Tags: .net, c#, fluent interface, console

Create new console app

Either through VS or:

dotnet new console -o 'QuickFluent' -n 'QuickFluent'

Write this into your main method in Program.cs:

Fluent fluent = new Fluent();
fluent.Hi()
    .How()
    .Are()
    .You();

This will not work yet, as you can guess. And also, why am I not yet using an interface? Because we will use a little trick to get this set up quickly, using VS.

Now click on Fluent class and hit ‘CTRL + .’, and generate the class into a new file. Open the file and add the 4 methods in the following way:

internal class Fluent
{
    public Fluent()
    {
    }

    public IFluent Hi()
    {
        Console.WriteLine("Hi");
        return this;
    }
    public IFluent How()
    {
        Console.WriteLine("How");
        return this;
    }
    public IFluent Are()
    {
        Console.WriteLine("Are");
        return this;
    }
    public IFluent You()
    {
        Console.WriteLine("You");
        return this;
    }
}

Don’t worry about not having the IFluent interface yet. We can generate one by again hitting ‘CTRL + .’ on Fluent class. Choose ‘Extract Interface’, this will create an interface and implement it for the current class automatically. The interface will look like this:

internal interface IFluent
{
    IFluent Are();
    IFluent Hi();
    IFluent How();
    IFluent You();
}

Done! Now instead of this:

Fluent fluent = new Fluent();
fluent.Hi();
fluent.How();
fluent.Are();
fluent.You();

you can use this:

IFluent fluent = new Fluent();
fluent.Hi()
    .How()
    .Are()
    .You();

or this, but be carefull not to create large unreadable trainwrecks:

IFluent fluent = new Fluent();
fluent.Hi().How().Are().You();