Saturday, October 31, 2009

.net 3.5 Extension Methods, Its a syntactiv sugar.

Using extension methods and object oriented techniques, this is the best example i have come across.

public static void DoIt()
{
var someMeeting = Meeting.Between("jack").And("jill").At(8.OClock().Tommorrow());
}

Other than some basic Oops inheritance, what is used here is Extension methods which i would put here. So, in a way extension methods help in writing a more compact code (syntactic sugar) , which is not always possible using inheritance, polymorphism.


public static class Extensions
{
public static TimeSpan OClock(this int hour)
{
return new TimeSpan(hour, 0, 0);
}

public static DateTime Tommorrow(this TimeSpan time)
{
return new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, time.Hours, time.Minutes, time.Seconds);
}
}

No comments:

Post a Comment