Home » C# | Software Developement

C# Extension Method example

11. October 2008 by Dave Hawes 2 Comments

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   {
   3:          public static DateTime EndOfDay(this DateTime input)
   4:          {
   5:              return new DateTime(input.Year, input.Month, input.Day, 23, 59, 59, 59);
   6:          }
   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!


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

Technorati Tags: ,,


secret of roulette casino
United States secret of roulette casino said:

I simply could not depart your site prior to suggesting that I actually enjoyed the standard info an individual supply on your guests? Is going to be back frequently to inspect new posts.

Melvin Minshew
United States Melvin Minshew said:

CCLEUNG Web Design Company, Our web designer is able to create complete eCommerce web sites. This includes unlimited adding, editing or deleting categories, products, information pages, and manufacturer information. We support multi-currency, product reviews, product ratings, multiple tax rates, related products, shipping weight calculation, discount coupon system, printable invoices and sales reports. http://www.ccleungwebdesign.com/

Comments are closed