Skip to content
Tags

,

Extension Methods in .NET 2.0

April 4, 2008

One of my favorite new features of C# 3.0 are extension methods. However, for some projects I’m not willing or able to target version 3.5 of the .NET framework. Up until today I thought that this meant I was out of luck in terms of being able to use extension methods, until Scott Hanselman’s post about them got the gears turning in my head.

If you try to add an extension method in a project that targets version 2.0 of the .NET framework, you’ll get an error saying you have to reference System.Core. However, the error is misleading. Extension methods are just normal static methods tagged with the [Extension] attribute. This attribute is actually just added by the compiler behind the scenes. In .NET 3.5, it lives in System.Core, but if you define your own attribute like this:

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

Your extension methods will suddenly spring to life! After testing, I realized I’m not the first one to figure this out, but it’s definitely something I’ll keep in my bag of tricks.

About these ads

From → miscellaneous

3 Comments
  1. I’ve been doing this for a while now using LinqBridge:

    http://www.albahari.com/nutshell/linqbridge.html

    Only thing I can say is that Resharper 4 EAP doesn’t seem to believe me and attempts to restructure my methods into Enumerable.Where(…) instead when doing code cleanup etc.

    Other then that it’s all good :)

  2. I’ve got this piece of C# 3.0 that I’m trying to run under C# 2.0:

    static class FormExtensions {
    static public void UIThread(this Form form, MethodInvoker code) {
    if (form.InvokeRequired) {
    form.Invoke(code);
    return;
    }
    code.Invoke();
    }
    }

    I added your helpful code snippet above the namespace for my project, but neither Intelliscense nor the compiler would allow it.

    The key problem here is finding out how to use “this Form form”.

    Am I using your snippet incorrectly or is your solution not relevant?

    Thanks,
    Joe

Trackbacks & Pingbacks

  1. .net 3.0 – Extension Methods « .net and everything else….

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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: