Dave Hawes Blog
A view on software development

C# Extension Method example

October 11, 2008 20:01 by davehawes

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

 

Technorati Tags: ,,
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: C# | Software Developement
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading