Jaycent Drysdale

Extension Methods: A simple example

If you've been developing software for any significant lenght of time, chances are you have compiled(for want of a better word) a repository of helper functions that have, over time, become valuable to you as you make your way through various applications. Extension Methods allow us to extend our custom and existing CLR types to include new functionality. These new functionality might already exist in the form of helper functions scattered throughtout our applications. For example, You might have a helper function that converts a string value to Proper Case. Extension methods allow us to "add" this ToProperCase() functionality to the primitive System.String type as if it were a built in method of the type. 

In this post, I'll share with you a simple example of how I used extension methods to extend the sealed System.DateTime native type to include a
ToFriendlyDateString() method. Extension Methods are new in the .Net Framework 3.5.

The idea behind the ToFriendlyDateString() method is representing dates in a user friendly way. For example, when displaying a news article on a webpage, 
you might want articles that were published one day ago to have their publish dates represented as "yesterday at 12:30 PM". Or if the article was publish today,
show the date as "Today, 3:33 PM". 

The code snippet below shows the logic that will represent our extension method. Note the Namespace declaration, and the signature for the class definition. Note also the use of the this keyword when describing the input parameter for the ToFriendlyDateString() method. I'll eloberate on these later in this discussion.

namespace Utils
{
     public static class Extensions
       
{
            
public static string ToFriendlyDateString(this DateTime Date) 
             
{
                    
string FormattedDate = "";
                    
if (Date.Date == DateTime.Today)
                    
{
                           FormattedDate =
"Today";
                    
}
                    
else if (Date.Date == DateTime.Today.AddDays(-1)) 
                    {
                           FormattedDate =
"Yesterday"; 
                    }
                    
else if (Date.Date > DateTime.Today.AddDays(-6))
                    {
                           // *** Show the Day of the week
                          
FormattedDate = Date.ToString("dddd").ToString(); 
                    }
                    else
                   
{
                          FormattedDate = Date.ToString(
"MMMM dd, yyyy");
                    }

                  
//append the time portion to the output
                 
FormattedDate += " @ " + Date.ToString("t").ToLower();
                 
return FormattedDate; 
             }
        }
} 

When creating extension methods, here are the rules

  • You must define a namespace for your class.  Utils in the snippet above (Namespaces are not a strict requirement, but good practice nevertheless)
  • The class that contain the extension method must be decorated with the static modifier, and its visibility must be public
  • The class must contain a static member, which will act as the extension method. This method must be public and must take one or more parameters, the first which must be a derivitive of the type you are extending. The first parameter definition must be preceeded by the this keyword

Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive. See example below showing how we might use the ToFriendlyDateString() method in our applications:

using Utils;

......

DateTime dt = new DateTime(2008, 2, 10, 8, 48, 20);
Console.WriteLine(dt.ToFriendlyDateString());

For further details on Extension Methods, check out this MSDN link: http://msdn2.microsoft.com/en-us/library/bb383977.aspx

Comments

Jesse Ezell said:

You should clarify or correct this:

"This extension method must be public and must take one parameter"

Extension methods are not restricted to a single parameter.

# February 12, 2008 10:33 AM

Fons Sonnemans said:

I have published your example on www.extensionmethod.net/Details.aspx

I hope you don't mind.

# February 12, 2008 4:21 PM

jaycent said:

To Jesse:- I made the update. Thanks for catching that.

To Fons:- No problem!

# February 13, 2008 1:47 PM

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# February 16, 2008 1:09 AM

Miron said:

Very nice and very useful article.

Thanks

# February 16, 2008 3:48 PM

Bart Czernicki said:

"You must define a namespace for your class.  Utils in the snippet above"

This is not true either.  You should do it to prevent collisions when the same method name appears.  However, this is not a must.

# February 18, 2008 5:48 PM

jaycent said:

Bart...if you know of another way to bring extension methods into scope in the consuming application, please share it! All the documentation I've seen to date on extension methods require that the class containing the methods be wrapped in a namespace, and that namespace must be imported into the consuming application. I'm curious to know if there is another way to do this.

Bart, you were correct..my apologies...explicit namespaces are not a strict requirement for working with extension methods...but good practice none-th-less. thanks for pointing that out.

# February 18, 2008 9:49 PM

SonOfPirate said:

jaycent: All you need to do is add a "using" statement referring to the namespace containing your extensions and they will be available to your code.  This assumes that you've also added the necessary reference to the assembly, of course.

# February 19, 2008 10:00 AM

Chinese Horoscope said:

I wish finding over a broken heart is usually so easy as following a couple of steps..<br> but its not…

--------------------------------------------

my website is  

http://www.mysticgrass.com

Also welcome you!

# November 18, 2010 11:02 AM

ipad app development said:

He that makes a good war makes a good peace.

-----------------------------------

# December 18, 2010 1:33 PM

best ipad accessories said:

-----------------------------------------------------------

"As a Newbie, I am generally browsing on the internet for articles that can aid me. Say thanks to you"

# January 3, 2011 8:58 AM

ipad app said:

-----------------------------------------------------------

amazing stuff thanx

# January 8, 2011 7:40 AM

pc game reviews said:

"Sometimes i would like to think that folks would just get a life and realize how silly they seem to be. I mean, why are you currently spamming, is it a way of hacking or  something. Just cease, please, i prefer to learn other people opinions too ya know. anyhow, excellent submit. just get rid of your spam please. thanks."

# February 10, 2011 6:16 PM

Jagan said:

Very effective & useful article i've found here.

Thanks a lot for share this informative posting !!

 - Uselogodesigns( <a href="http://www.uselogodesigns.com">cheapest logo designs<a/> )

# June 17, 2011 11:40 PM

Dewitt Lammers said:

The very heart of your writing though appearing reasonable originally, did not settle properly with me personally following some time. Someplace throughout the sentences you in fact managed to make me a believer but only for a short whilst. I nevertheless have got a issue with your leaps in logic and you might do nicely to fill in those breaks. When you really can accomplish that, I could surely be fascinated.

# July 1, 2011 3:46 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)