Fluent API’s using Extension Methods

Introduction

Fluent API’s are very readable API and Often uses method chaining to make code read like a sentence. You can only create fluent API’s using Extension methods

For example if we want to build a date time structure like 2 Hours Before.

var timeBeforeTwoHours = 2.Hours().Before();

The way we to do is write an extension method for int called Hours and an extension method for TimeSpan  called Before and the end result could be the date time before  2 hours.

public static TimeSpan Hours(this int value)
{
return new TimeSpan(0,2,0,0,0);
}
public static  DateTime Before(this TimeSpan value)
{
return DateTime.Now - value;
}

Full Code

static class Program
{
static void Main(string[] args)
{
var timeBeforeTwoHours = 2.Hours().Before();
}
public static TimeSpan Hours(this int value)
{
return new TimeSpan(0,2,0,0,0);
}
public static  DateTime Before(this TimeSpan value)
{
return DateTime.Now - value;
}
}

Enjoy coding…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s