Extension Methods in .NET 2.0

by Nate on 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.

Share this post:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DotNetKicks
  • DZone
  • FriendFeed
  • HackerNews
  • Posterous
  • Reddit
  • Twitter

Related posts:

  1. EventHandler Extension Method
  2. Attributes? We Don’t Need No Stinkin’ Attributes
  3. Ninject and AOP

{ 1 trackback }

.net 3.0 – Extension Methods « .net and everything else….
March 9, 2010 at 7:47 am

{ 2 comments… read them below or add one }

Alex Henderson April 22, 2008 at 6:07 pm

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 :)

Joe Pool June 26, 2009 at 12:11 pm

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

Leave a Comment

Previous post: New Design for Ninject

Next post: This is why we can’t have nice things, people