Extension Methods - Part 2 - Behind the scenes

In Part one we looked at how extension methods are implemented, and what they do. It is indeed very clever, but how does it work?

Lets fire up Ildasm and a have a look at what is really going on behind the scenes.

testmethodil_thumb[1]

Looking at the IL for the example in part one we notice that the method call to the extension method is actually just translated to a static call to the method we implemented in the Extensions class.

extensionsil_thumb[4]

And we see that the Extension method has been translated to a static method with the attribute "ExtensionAttribute" indicating that its an extension method.

So actually there is nothing new in the IL to make this happen - the CLR is the same, its simply compiler magic where the ExtensionAttribute (set via the this shortcut in the method signature) ensures that a call to an extension method resolves to a another static method in the IL.

This means that you could actually use extension methods in .Net 2.0 projects. Yes its actually true!

If you take the above implementation and change the target framework to .Net 2.0 in Visual Studio 2008's multi targeting environment, and compile you will get the following error:

Error    1    Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll?

Obviously you are missing the ExtensionAttribute, and you don't want to add a reference to System.Core. But as the this attribute is only needed as an indicator at compile time, you can actually just create the attribute yourself like so:

namespace System.Runtime.CompilerServices
{
    public class ExtensionAttribute : Attribute { }

}

And it compiles and runs. Logical, but a little surprising none the less. See Daniel Moths original post.

So Extension methods are actually sweet syntactic sugar that doesn't add anything to the class, and that is brought to life by a very clever compiler, without ever touching the CLR.

In my next post, I will take a stab at some best practices for the use of extension methods.

Posted April 25, 2008 by Joachim Lykke Andersen
In

Comments [0]   
All comments require the approval of the site owner before being displayed.
OpenID
Please login with either your OpenID above, or your details below.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview