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

jaycent said:

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

To Fons:- No problem!

# February 13, 2008 1:47 PM

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

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

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

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

reriAcroria said:

QWERADFHGDAFASDGHASD  FGBNFSDGSADADFHAD

ERYERSDGSADXZCBZX  ADFHGASDGASDADSFHGADFS

ASFDSDGSADADFHAD  QWERADFHGDAFSDAFHSAD

SDGSDADFGASDGDFHAD  ZVXZADFGASDGDFHAD

# August 27, 2012 12:29 AM

Asteleplorept said:

ASFDASDGASDSDFH  DSGASDGSADADFHGAD

SDGSDZSDGASDDSFGHADS FGBNFADFGASDGADFHGAD

QWERADFHGDAFDFHAD FGBNFASDGASDASDGHASD

SDGSDSDGSADDSFGHADS SDGSDSDGSADGADSFHGADFS

# August 27, 2012 2:33 AM

Ames said:

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?

# August 29, 2012 12:19 PM

chuslyurgerse said:

YUKYSDGSADGSDAFHSAD  ADFHGADFHGDAFADFHAD

DSGASDGSADSDGASD  ADFHGSDGSADSDAFHSAD

ERYERSDGSADSDFH  ADFHGSDGSADGXZCBZX

DSGASDGSADADSFHGADFS  GJTRSDGSADADFHAD

# August 31, 2012 2:11 PM

GafeWrofe said:

FGBNFSDGSADGSDAFHSAD  GJTRZSDGASDADSFHGADFS

ADFHGASDGASDSDFH FGBNFADFHGDAFASDGHASD

ERYERSDGSADGASDGHASD ZVXZZSDGASDSDGASD

ZVXZSDGSADDFHAD SDGSDADFGASDGSDAFHSAD

# September 4, 2012 4:25 PM

Absordreibe said:

ERYERSDGSADSDAFHSAD  SDGSDADFGASDGSDFH

ADFHGADFHGDAFSDAFHSAD  ASFDADFHGDAFADFHGAD

ERYERSDGSADDFHAD  ERYERSDGSADASDGHASD

ZVXZADFHGDAFADSFHGADFS  ADFHGSDGSADGDFHAD

# September 5, 2012 5:23 PM

Blawlnard said:

ASFDADFHGDAFASDGHASD  SDGSDSDGSADADSFHGADFS

QWERSDGSADASDGHASD  ZVXZADFGASDGXZCBZX

ERYERASDGASDASDGHASD  ADFHGADFHGDAFASDFHGAD

DSGAZSDGASDDFHAD  YUYSDGSADADFHGAD

# September 20, 2012 1:35 AM

Choifebiole said:

YUKYASDGASDASDGHASD  QWERADFGASDGSDAFHSAD

FGBNFSDGSADGSDFH  DSGASDGSADDSFGHADS

YUKYSDGSADGADFHAD  ERYERSDGSADASDFHGAD

YUKYSDGSADSDFH  FGBNFZSDGASDSDFH

# September 20, 2012 9:09 PM

Timmons said:

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

self anyone?

# October 18, 2012 9:21 AM

Stine said:

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.

# October 19, 2012 1:23 AM

Martin said:

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!

# December 16, 2012 9:26 PM

Peel said:

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

# December 21, 2012 11:12 AM

Wheatley said:

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!

# January 6, 2013 2:31 AM

Martindale said:

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.

# January 6, 2013 9:03 PM

Bright said:

Hi, I wish for to subscribe for this blog to

get hottest updates, so where can i do it please help out.

# January 8, 2013 12:17 AM

Kruse said:

I am sure this article has touched all the internet visitors, its really really pleasant piece of writing

on building up new web site.

# January 29, 2013 2:03 AM

Mullis said:

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

# April 8, 2013 8:26 PM

Grenier said:

I know this site provides quality dependent content and other data,

is there any other site which presents such information in quality?

# April 15, 2013 1:27 AM

xejuxwqfy said:

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><b>&#12459;&#12471;&#12458; &#26178;&#35336;</b></a>

<a href=http://www.mcm-newjps.com><b>mcm</b></a>

<a href=http://www.mcm-newonlines.com><b>&#28608;&#23433;MCM</b></a>

<a href=http://www.mcm-newoutlet.com><b>MCM &#36001;&#24067;</b></a>

<a href=http://www.jpbagsstore-mcm.com><b>mcm &#12522;&#12517;&#12483;&#12463;</b></a>

<a href=http://www.newmcmjp-2013bags.com><b>MCM&#36001;&#24067;</b></a>

<a href=http://www.japanmcmsale-bags.com><b>MCM &#12496;&#12483;&#12464;</b></a>

<a href=http://www.cheaplv-jashop.com><b>&#12532;&#12451;&#12488;&#12531;</b></a>

<a href=http://www.cheaplv-jastore.com><b>&#12523;&#12452; &#12532;&#12451;&#12488;&#12531;</b></a>

<a href=http://www.cheaplv-jamall.com><b>&#12532;&#12451;&#12488;&#12531;</b></a>

# May 30, 2013 11:49 AM

sbpziyegj said:

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><b>chanel &#12496;&#12483;&#12464;</b></a>

<a href=http://www.autorettosyaneru1.com><b>&#12471;&#12515;&#12493;&#12523; &#12496;&#12483;&#12464;</b></a>

<a href=http://www.onnrainsyaneru1.com><b>&#12471;&#12515;&#12493;&#12523;</b></a>

<a href=http://www.yuuguusyaneru1.com><b>chanel &#36001;&#24067;</b></a>

<a href=http://www.saisinsyaneru1.com><b>&#12471;&#12515;&#12493;&#12523; &#36001;&#24067;</b></a>

<a href=http://www.sunglasseshotjps.com><b>&#12469;&#12531;&#12464;&#12521;&#12473;&#12450;&#12454;&#12488;&#12524;&#12483;&#12488;</b></a>

<a href=http://www.sunglassesjapancheap.com><b>&#12524;&#12452;&#12496;&#12531; &#12469;&#12531;&#12464;&#12521;&#12473;</b></a>

<a href=http://www.jpsunglassesyahoo.com><b>&#12458;&#12540;&#12463;&#12522;&#12540;</b></a>

<a href=http://www.homesunglassesjpsale.com><b>&#12502;&#12521;&#12531;&#12489; &#12469;&#12531;&#12464;&#12521;&#12473;</b></a>

<a href=http://www.sungalassesjpsite.com><b>RayBan&#12524;&#12452;&#12496;&#12531;&#28608;&#23433;</b></a>

# May 30, 2013 12:19 PM

vusdmyuwj said:

Thanks  for any other informative web site.

?a href="http://www.jpmbtnew-store.com"><b>MBT&#20605;&#29289;</b></a>

<a href="http://www.celinegento.com"><b>&#12475;&#12522;&#12540;&#12492;</b></a>

<a href="http://www.watchyasoi.com"><b>&#26178;&#35336; &#12513;&#12531;&#12474;</b></a>

<a href="http://www.watchgento.com"><b>&#33109;&#26178;&#35336; &#12513;&#12531;&#12474; &#20154;&#27671;</b></a>

<a href="http://www.hamiltonjpswatch.com"><b>&#12495;&#12511;&#12523;&#12488;&#12531; &#26178;&#35336;</b></a>

<a href="http://www.japanhamiltonshop.com"><b>&#12495;&#12511;&#12523;&#12488;&#12531;&#33109;&#26178;&#35336;</b></a>

<a href="http://www.baghermesoutlet.com"><b>&#12456;&#12523;&#12513;&#12473; &#36001;&#24067; &#26032;&#20316;</b></a>

<a href="http://www.hermesjpshomebag.com"><b>&#12456;&#12523;&#12513;&#12473; &#36001;&#24067;</b></a>

<a href="http://www.cheaphamiltonsale.com"><b>&#33109;&#26178;&#35336; hamilton</b></a>

<a href="http://www.tumibagsjp.com"><b>tumi &#12496;&#12483;&#12464;</b></a>

<a href="http://www.miumiu2013hotsale.com"><b>&#12511;&#12517;&#12454;&#12511;&#12517;&#12454; &#36001;&#24067;</b></a>

<a href="http://www.miumiuonlineshopjp.com"><b>&#12511;&#12517;&#12454;&#12511;&#12517;&#12454;</b></a>

# June 5, 2013 2:27 PM