Thursday, March 6, 2014

C# is pretty expresive too

I just saw this post , about how to add methods to types in F# (and referencing another in rust), so you can make words like Months and Ago have meaning and allow you to say things like '3 years ago'. Since C# now has extension methods, I figured I'd try to see how it could be done in C#

public static class MyExtensions
{
public static System.TimeSpan Months(this Int32 x)
{
return System.DateTime.Today.AddMonths(x) - System.DateTime.Today;
}
public static System.TimeSpan Years(this Int32 x)
{
return System.DateTime.Today.AddYears(x) - System.DateTime.Today;
}
public static System.TimeSpan Years(this Double x)
{
return System.DateTime.Today.AddDays(x) - System.DateTime.Today;
}
public static System.DateTime Ago(this System.TimeSpan x)
{
return System.DateTime.Now.Add(x.Negate());
}
public static System.DateTime FromNow(this System.TimeSpan x)
{
return System.DateTime.Now.Add(x);
}
public static System.DateTime FromToday(this System.TimeSpan x)
{
return System.DateTime.Today.Add(x);
}
}
void Main()
{
Console.WriteLine(3.Months().Ago());
Console.WriteLine(3.Years().FromToday());
}

So, what do you think ?

BTW, I tested this in LinqPad, may need something extra to become a full program