Extension methods in .NET 2.0

Due to the nature of our client base, we still target .NET 2.0 at work. The side-effect being, of course, the inability to use the latest and greatest and sexiest of what C# has to offer these days.

I was setting out to write some static helper methods this morning, and on a lark decided to Google for extension method support. Sometimes the compiler is nice enough to take 3.0 features (such as the var keyword) and translate them into code that’s palatable for .NET 2.0.

Truly, ask and ye shall receive! Success! While in newer versions of the framework, you’d import System.Core.dll to add extension support, all that’s really needed is the definition of the ExtensionAttribute class. This can be added anywhere in your code that targets .NET 2.0:

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

Extensions work like a charm after that.

Advertisements
Next Post
Leave a comment

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: