Entries
RSS 2.0

Comments
RSS 2.0

Extension Methods in .NET 2.0

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.

1 comment so far

  1. Alex Henderson April 22, 2008 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 :)

Leave a comment

Please be polite and on topic. Your e-mail will never be published.