# Friday, October 05, 2007

With the power of Extension Methods introduced in C# 3.0, you can design a Fluent Interface that gives the Ruby date syntax mentioned in this article on the beauty of Ruby's readability:

20.minutes.ago

a good run for its money.

With the basics of extension methods understood, attaining this syntax takes only the simple addition of a class with 2 extension methods (note the new "this" keyword as a method argument):
public static class MyExtensions
{

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

    public static DateTime ago(this TimeSpan timeSpan)
    {
        return DateTime.Now.Add(timeSpan.Negate());
    }

}

And now we have a the Ruby-like date syntax (at least for minutes) in C#:

20.minutes().ago()

Since the above code would return a DateTime object, here is an example usage:

if (startDate < 20.minutes().ago())
{
    Console.Out.WriteLine("Started over 20 minutes ago");
}
Implementing hours, seconds, etc. would also be trivial and the "ago" extension method is re-usable for all TimeSpans.

And this ability is not limited to just Ruby's date syntax. The usefulness of Extension Methods also allow for design of fluent interfaces that resemble other Ruby syntax, I just chose the "minutes" one as a simple example that I could develop quickly.

If you found this post helpful, please "Kick" it so others can find it too:

kick it on DotNetKicks.com
All comments require the approval of the site owner before being displayed.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: b, blockquote@cite, em, i, strike, strong, sub, sup, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview