Skip to the content Back to Top

There's been a lot of excitement about a new language feature in the .NET Framework 3.5 "Orcas": extension methods.

Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. -- ScottGu's Blog

That's High Geek for "you can tack on methods to existing .NET classes." For example, you could extend the String class with a UrlEncode method:

C# Extension Method: UrlEncode

public static string UrlEncode(this string s)
{
    return HttpUtility.UrlEncode(s);
}

Then you could call it from any string:

string str = "blah";
string strEncoded = str.UrlEncode();

That's all very useful, and I'll make heavy use of it, I'm sure. It's not exactly new, though. Javascript has had extension methods on offer for years with the prototype object. Entire javascript frameworks have been built around it: Prototype, mootools, jQuery, etc. Taking the above UrlEncode example:

Javascript Extension Method: UrlEncode

String.prototype.UrlEncode = function()
{
    return encodeURIComponent(this);
}

So, as far as the coming extension methods in .NET go, I guess I'm less "wow, neato" and more "it's about time." I'm *such* a jerk.

Let Us Help You!

We're Librarians - We Love to Help People