Sunday, November 16, 2008

.NET 2.0 Extension Methods

I regularly write programs in C# on Visual Studio 2008. The default Framework for the environment is 3.5. But sometimes I must re-target 2008 to Framework 2.0. Is it possible to take advantage of the new "Extension Method" language feature of 2008 when required to target 2.0? This is a good question and applies to more than the extension methods. But for now, let's answer the question for extensions.

Yes.

But, you need to do some of the work yourself. The compiler's support for extension methods is really unconnected with Framework 3.5. But maybe you've seen the 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?


To write an extension, you need the ExtensionAttribute somewhere, anywhere. The compiler is looking for it in the System.Runtime.CompilerServices namespace which is in System.Core.dll. The 2.0 and 3.5 versions of this DLL are different. The good news is you don't need the whole 3.5 DLL, you just need the ExtensionAttribute class and you can actually write it yourself.

So, here I have written the class you need in C#.

namespace System.Runtime.CompilerServices
{
    [AttributeUsage(
        AttributeTargets.Assembly
        |AttributeTargets.Class
        |AttributeTargets.Method,
        Inherited=false,
        AllowMultiple=false)
    ]
    public class ExtensionAttribute : Attribute
    {
    }
}

Add this to a new class file or an existing file. Make sure you add it outside of all other namespace definitions since you will be adding to the System.Runtime.CompileServices namespace.

That's all it should take. Good luck with your projects and using extension methods in C# with Framework 2.0.

No comments: