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

31 Comments

  • 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.

  • To Jesse:- I made the update. Thanks for catching that. To Fons:- No problem!

  • Very nice and very useful article.
    Thanks

  • "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.

  • 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.

  • He that makes a good war makes a good peace.

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

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

  • -----------------------------------------------------------
    amazing stuff thanx

  • "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."

  • 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.

  • QWERADFHGDAFASDGHASD FGBNFSDGSADADFHAD
    ERYERSDGSADXZCBZX ADFHGASDGASDADSFHGADFS
    ASFDSDGSADADFHAD QWERADFHGDAFSDAFHSAD
    SDGSDADFGASDGDFHAD ZVXZADFGASDGDFHAD

  • ASFDASDGASDSDFH DSGASDGSADADFHGAD
    SDGSDZSDGASDDSFGHADS FGBNFADFGASDGADFHGAD
    QWERADFHGDAFDFHAD FGBNFASDGASDASDGHASD
    SDGSDSDGSADDSFGHADS SDGSDSDGSADGADSFHGADFS

  • Now i'm starting to enter pool and also decided to get my own "cue". I like the European taper about snooker cues far more then the expert tapers on Us pool cues, but Now i'm not sure if it's okay will utilize a snooker cue for eight ball. I am aware it's granted, but My spouse and i heard the solid wood can
    split quickly and tips will have to be exchanged very often
    any time playing American billiards with a snooker "cue". Can any person confirm this specific?

  • YUKYSDGSADGSDAFHSAD ADFHGADFHGDAFADFHAD
    DSGASDGSADSDGASD ADFHGSDGSADSDAFHSAD
    ERYERSDGSADSDFH ADFHGSDGSADGXZCBZX
    DSGASDGSADADSFHGADFS GJTRSDGSADADFHAD

  • FGBNFSDGSADGSDAFHSAD GJTRZSDGASDADSFHGADFS
    ADFHGASDGASDSDFH FGBNFADFHGDAFASDGHASD
    ERYERSDGSADGASDGHASD ZVXZZSDGASDSDGASD
    ZVXZSDGSADDFHAD SDGSDADFGASDGSDAFHSAD

  • ERYERSDGSADSDAFHSAD SDGSDADFGASDGSDFH
    ADFHGADFHGDAFSDAFHSAD ASFDADFHGDAFADFHGAD
    ERYERSDGSADDFHAD ERYERSDGSADASDGHASD
    ZVXZADFHGDAFADSFHGADFS ADFHGSDGSADGDFHAD

  • ASFDADFHGDAFASDGHASD SDGSDSDGSADADSFHGADFS
    QWERSDGSADASDGHASD ZVXZADFGASDGXZCBZX
    ERYERASDGASDASDGHASD ADFHGADFHGDAFASDFHGAD
    DSGAZSDGASDDFHAD YUYSDGSADADFHGAD

  • YUKYASDGASDASDGHASD QWERADFGASDGSDAFHSAD
    FGBNFSDGSADGSDFH DSGASDGSADDSFGHADS
    YUKYSDGSADGADFHAD ERYERSDGSADASDFHGAD
    YUKYSDGSADSDFH FGBNFZSDGASDSDFH

  • Is There away to learn yu gi oh yea using the pc aganst many people or by you
    self anyone?

  • I want to protect the completely new yu gi also cards u was questioning if baseball masturbator sleeves work
    because my local store merely has hockey card sleeves.

    Their not necessarily too big as well as too small as well as
    anything proper? Thanks a lot.

  • Greetings! I've been reading your web site for a while now and finally got the bravery to go ahead and give you a shout out from New Caney Tx! Just wanted to mention keep up the fantastic work!

  • Paragraph writing is also a excitement, if you be familiar with afterward you can write or else it is complicated to write.

  • Wow that was odd. I just wrote an extremely long comment but after I clicked submit my comment didn't show up. Grrrr... well I'm not writing all that over again.
    Anyways, just wanted to say wonderful blog!

  • What's up everybody, here every person is sharing these know-how, so it's
    fastidious to read this blog, and I used to pay
    a quick visit this web site every day.

  • Hi, I wish for to subscribe for this blog to
    get hottest updates, so where can i do it please help out.

  • I am sure this article has touched all the internet visitors, its really really pleasant piece of writing
    on building up new web site.

  • Very energetic post, I liked that a lot. Will there be a part 2?

  • I know this site provides quality dependent content and other data,
    is there any other site which presents such information in quality?

  • Marshall, MI (Weekend Trips)Little Marshall, Michigan, has experienced a lot of statements to fame via the years. Early within the 1840s, this Calhoun County city was self-confident of getting chosen to exchange Detroit because the state's money. Marshall, .
    ?a href=http://www.casiowatch-japan.com>カシオ 時計
    mcm
    激安MCM
    MCM 財布
    mcm リュック
    MCM財布
    MCM バッグ
    ヴィトン
    ルイ ヴィトン
    ヴィトン

  • Merely wanna remark on few general things, The website style is perfect, the subject matter is very fantastic. "In business school classrooms they construct wonderful models of a nonworld." by Peter Drucker.
    ?a href=http://www.hannbaisyaneru1.com>chanel バッグ
    シャネル バッグ
    シャネル
    chanel 財布
    シャネル 財布
    サングラスアウトレット
    レイバン サングラス
    オークリー
    ブランド サングラス
    RayBanレイバン激安

  • Thanks for any other informative web site.
    ?a href="http://www.jpmbtnew-store.com">MBT偽物
    セリーヌ
    時計 メンズ
    腕時計 メンズ 人気
    ハミルトン 時計
    ハミルトン腕時計
    エルメス 財布 新作
    エルメス 財布
    腕時計 hamilton
    tumi バッグ
    ミュウミュウ 財布
    ミュウミュウ

Comments have been disabled for this content.