Introduction:
Published on March 17 2008, Mike Gold wrote an excellent article on extension methods, where he extended the System.String class with some old favourites such as Left, Right and Mid.
Multi-targeting
Visual Studio 2008 implements what is called 'multi-targeting' - in other words, you can select the version of the .NET Framework you wish to work with (V2.0, V3.0 and V3.5). Now, anyone who has selected the target framework to be anything other than version 3.5 and tried to use extension methods will receive the following compilation error:
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?
System.Core.dll is new to V3.5 of the .NET Framework and ExtensionAttribute is defined in this assembly, so there are no surprises that we receive this compilation error, as System.Core.dll cannot be found.
So, it looks as though we cannot use extension methods in our projects within VS2008 if they are targeted for anything other than v3.5 of the framework,well not quite, armed with a copy of Reflector we can take a look at this attribute, which reveals the following:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
public sealed class ExtensionAttribute : Attribute
{
}
So, in order to get extension methods to work, it should be a matter of recreating this attribute in the System.Runtime.CompilerServices namespace, as follows:
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
public sealed class ExtensionAttribute : Attribute
{
}
}
Do this and re-compile your code and you will find that extension methods will work. To help re-use, this attribute could be put in its own class and compiled, then simply reference the assembly when you need to create extension methods. The accompanying VS2008 solution file has this attribute in a separate class file for you to make use of.
Conclusion
Extension methods, used wisely, are quite a useful feature. If you are going to be using Visual Studio 2008 multi-targeting feature to target your application at a version of the framework other than v3.5, using the method shown above, you will be able to make use of extension methods.