Extension methods in .NET 3.5 – cool stuff!!

One of the new features in .NET 3.5 are extension methods. These are a way you can sort of "tack on" some additional methods for a data type, without modifying or inheriting from the actual data type. ScottGu talked about it over here: http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx

So one of the things I was thinking – was how to best use this? It has some definite pros and cons. The pros should be obvious – one can keep the .NET run-time and developed components much simpler, because you don’t need to inherit from a class to make slight enhancements to it. One of the cons would be that this can end up making intellisense difficult to use because of too MUCH functionality.

For example, I was thinking "what extensions would I add to System.String?". The first thing that came to mind was – every single .Parse and .TryParse that I use all the time. Using extension methods, I could make it slightly easier to deal with converting a string into an int, DateTime, Uri, etc. So, let’s start with this. Below is a class that applies extension methods to System.String:

Download: StringExtensions.cs

So this is how this changes System.String:



So again, I am on the fence whether this is better, worse or just a wash. For example, in code, here is what this did for us:

    string testString = "14";

    long theCount = -1;


    if (long.TryParse(testString, out theCount))



        MessageBox.Show("Couldn’t parse");

And with the extension method, here’s how this translates:

    string testString = "14";

    long theCount = -1;


    if (testString.TryParseAsLong(out theCount))



        MessageBox.Show("Couldn’t parse");

I like the idea of this functionality being pushed back to the type, so that the code appears to stay with the string (versus getting "long" involved) – but I wonder if the fact that isn’t consistent, makes it not worth doing. If I had 1 huge project or a developer framework – I might add this perhaps – but I suppose .NET 3.5 will need to age a little bit to see where extension methods end up being most useful!

Posted in .NET 3.5, Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.


Enter your email address to follow this blog and receive notifications of new posts by email.

Join 9 other followers

%d bloggers like this: