I was told about a new feature in C# 3.0 called extension methods back in 2007 sometime by the technical architect at my old company. He explained that Microsoft had created it to enable LINQ and that it allows you extend base classes with your own functions, which is pretty cool. But what's a useful example?
Peter (my TA) said that creating a StartOfDay and EndOfDay function for the .Net DateTime class might be useful and today I needed those functions so I have decided to write them blog how I did it.
1: public static class ExtensionMethods {
2:
3: public static DateTime EndOfDay(this DateTime input)
4: {
5: return new DateTime(input.Year, input.Month, input.Day, 23, 59, 59, 59);
6: }
7:
8: public static DateTime StartOfDay(this DateTime input)
9: {
10: return new DateTime(input.Year, input.Month, input.Day, 00, 00, 00, 00);
11: }
12: }
So now I can write the following code as the .Net DateTime class now has my new functions included:
1: private static FieldBetweenPredicate AvailabilityFilter(DateTime selectedDate) {
2: return new FieldBetweenPredicate(PersonAppointmentsFields.StartDate, selectedDate.StartOfDay(), selectedDate.EndOfDay());
3: }
Thanks to David Hayden's blog for reminding me how to write them!
http://www.davidhayden.com/blog/dave/archive/2006/11/30/ExtensionMethodsCSharp.aspx
New note 02/Jan/2010: Just found another useful extension method for randomising a list: http://www.vbforums.com/showthread.php?s=51020c99595a4e123140a61ff2b00007&t=585855