Ruby is a very cool language, especially for meta-programming. The ability to extend any class is very powerful and can lead to a nice set of convenience methods. Rails in particular adds many, of which some are really popular since they read almost like English: 10.minutes.ago.
The .NET 3.5 does not bring us just LINQ and related functionality but also extension methods – a way to add a method to any class. This allows you to fairly easy replicate the example from above:
using System;
public static class Extensions {
public static TimeSpan Minutes(this int minutes) {
return new TimeSpan(0, minutes, 0);
}
public static DateTime Ago(this TimeSpan span) {
return DateTime.Now - span;
}
}
public class Program
{
public static void Main() {
DateTime now = DateTime.Now;
Console.WriteLine("It is now {0}, 10 minutes ago it was {1}", now, 10.Minutes().Ago());
}
}
You must reference System.Core.dll and implement your extension methods in a static class (whose name is not important). All extension methods must be static and have special first parameter this which denotes the target type you are extending. Running the above example produces:
It is now 31.8.2007 11:17:20, 10 minutes ago it was 31.8.2007 11:07:20
If you detest parenthesis, code this in VB.NET and you'll get almost a replica of Rails syntax.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5