Wednesday, November 12, 2008

How C# 3.0 helps you with creating DSL

Carrying on with the last post on how Method Chaining can help you create a DSL, I thought I would plagiarise some more content that Ian Cooper shared with us last night at the London DNUG.

Ian discussed the simple example of how in some languages it is very easy/readable to do something as simple as creating a DateTime of "20 minutes ago"

Ruby Code :

20.minutes.ago

C# Code:

DateTime.Now.AddMinutes(-20);

To be fair the C# code is not awful, but is less like a DSL and could be made a touch better. So how does C#3.0 help? Extension methods allow us to extend functionality of another type that we may not have defined. So in this example we can migrate to a Ruby style by implementing 2 extension methods.

public static TimeSpan Minutes(this int numberOfMinutes)
{
    return new TimeSpan(0, numberOfMinutes, 0);
}

public static DateTime Ago(this TimeSpan numberOfMinutes)
{
    return DateTime.Now.Subtract(numberOfMinutes);
}

By creating these extension methods we now give int types a new method Minutes() that returns a TimeSpan. We then extend the TimeSpan type to have an Ago() method that returns a DateTime. Very simple stuff that allows us to write code like this

20.Minutes().Ago();

Others have covered this topic before here

No comments: