Profile Picture

Sirwan Afifi

Stories from a web developer.

© 2017. Sirwan Afifi All rights reserved.

Designing Fluent Interfaces in C#

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:

using System;
using Microsoft.AspNetCore.Hosting;

namespace aspnetcoreapp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

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:

$('#result')
	.css('background', 'yellow')
	.width(200)
	.height(200)
	.text('This is the result');

For C#, there is LINQ:

var person = PersonDataSource
	.Where(p => p.Age > 20)
	.OrderBy(p => p.Name)
	.Select(p => new {
		Name = p.Name,
		LastName = p.LastName
});

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:

public class Calculator 
{
	public int Initial { get; private set; }
	public Calculator(int intial)
	{
		Initial = intial;
	}

	public Calculator Add(int x)
	{
		Initial = Initial + x;
		return this;
	}

	public Calculator Divide(int x)
	{
		Initial = Initial / x;
		return this;
	}

	public Calculator Substract(int x)
	{
		Initial = Initial - x;
		return this;
	}
}

Now we can use the class this way:

var calc = new Calculator(5)
			.Add(5)
			.Divide(5)
			.Substract(2);

System.Console.WriteLine(calc.Initial);

As you can see this approach makes our code concise and easier to read.

Explicit Interface Implementation

Let’s imagine that you have a class with two methods:

public class VendingMachine
{
    public bool InsertCoin(float amount)
    {
        if (amount < 500)
        {
            return false;
        }
        return true;
    }

    public string Buy()
    {
        return "Buy";
    }
}

Now when we want to create an instance of this class and call one of those methods, it executes as expected:

VendingMachine machine = new VendingMachine();
machine.InsertCoin(5); // false
machine.Buy();         // "Buy"

Now suppose that we have an interface called IVendingMachine that has two methods:

public interface IVendingMachine 
{
    bool InsertCoin(float amount);
    string Buy();
}

We want our class to implements this interface:

public class VendingMachine : IVendingMachine
{
    public bool InsertCoin(float amount)
    {
        if (amount < 500)
        {
            return false;
        }
        return true;
    }

    public string Buy()
    {
        return "Buy";
    }
}

Our class satisfied the interface because it has the methods with the same names. So Visual Studio doesn’t give you a compiler error. Now let’s imagine that we also want to add interface’s methods to this class, So, in this case, we must explicitly prefix the methods with IVendingMachine.:

public class VendingMachine : IVendingMachine
{
    public bool InsertCoin(float amount)
    {
        if (amount < 500)
        {
            return false;
        }
        return true;
    }

    bool IVendingMachine.InsertCoin(float amount)
    {
        if (amount < 300)
        {
            return true;
        }
        return false;
    }

    public string Buy()
    {
        return "Buy";
    }

    string IVendingMachine.Buy()
    {
        return "IVendingMachine Buy";
    }
}

Note that Visual Studio can help you to implement interface explicitly by pressing Ctrl + . on the name of the interface and select Implement interface explicitly:

Now, what happens when we call the InsertCoin and Buy methods? In this case, we should consider two different situations when we create the object:

  • Concrete Type
  • Interface Variable

If we want the methods of VendingMachine we should create the object with concrete type:

VendingMachine machine = new VendingMachine();
machine.InsertCoin(5); // false
machine.Buy();         // "Buy"

If we want the methods of IVendingMachine we should create the object with interface variable:

IVendingMachine machine = new VendingMachine();
machine.InsertCoin(5); // true
machine.Buy();         // "IVendingMachine Buy"

Delegates in C#

Lately I have been studying some topics in C# in order to improve myself. I think Delegate is one of those topics which is kinda difficult for beginners to initiate with. So, in order to make it clear how it works, I’m going to make some explanations in this post.

What are Delegates?

Delegate was introduced in C# 1. Think of it as a simply being a placeholder for functions that’ll be called at some point in time. Assume you want to declare a variable that is a reference to a specific method. In this case, the variable encapsulates some executable code and you can invoke the variable just like an actual method. In doing so, we need to create a delegate

Defining a Delegate

Delegates are created using delegate keyword along with the function signature:

delegate int Sum(int a, int b);

As you can see we are defining a delegate called Sum that is compatible with any method with an int return type with two parameters. Actually we defined a type that we can use to create variables and point those variables to methods that have the same signature and same return type. The type defenition for a delegate describes the method that we want to call:

int Add(int a, int b) => a + b;

Now we can assign a method to the delegate variable. This assignment creates a delegate instance:

Sum s = Add;

Now we can invoke the delegate instance in the same way as a method:

int result = s(5, 6);

Advantages of Delegate

  • Delegates are type safe, It means that the C# compiler checks the function signatures of a Delegate when you use them at runtime.
  • Can be used to define callback functions.
  • Can be dynamically switched at runtime.

Real World example

Suppose that you want to implement something like a Repeater control in your ASP.NET MVC application, As you probably know a Repeater is(was) server side databound control in ASP.NET WebForm for displaying information, It had a lot of flexability becuase you had complete control over the your markup.

public static class Helpers
{
	public delegate HelperResult ItemTemplate<T>(T input);

	public static HelperResult Repeater<T>(this HtmlHelper html,
	  IEnumerable<T> items,
	  ItemTemplate<T> itemTemplate,
	  ItemTemplate<T> alternatingitemTemplate = null)
	{
		return new HelperResult(writer =>
		{
			int i = 0;
			foreach (var item in items)
			{
				var func = i % 2 == 0 ? itemTemplate : alternatingitemTemplate;
				func(item).WriteTo(writer);
				i++;
			}
		});
	}
}

As you can see we emulated the ItemTemplate and AlternatingItemTemplate using a delegate. In this case user can pass the data and the data will be rendered inside the view. In this case the delegates act like callback.
The ItemTemplate delegate in our example can be replaced with Func delegate:

Func<T, HelperResult> itemTemplate,
Func<T, HelperResult> alternatingitemTemplate = null

Now we can use our helper inside any view:

<table>
    <tr>
        <td>Id</td>
        <td>Name</td>
    </tr>
    @Html.Repeater(Model, @<tr>
	    <td>@item.Title</td>
	    <td>@item.Price</td>
	</tr>, 
	@<tr class="alert-info">
	    <td>@item.Title</td>
	    <td>@item.Price</td>
    </tr>)
</table>

If you run the application you can see the result:

You can check out the GitHub repository for this post.