Geeks With Blogs
Running with Code Like scissors, only more dangerous

I was working on a series of dialogs that required validation, and since there's a funky validation setup in place, I thought I might build up a nice extension library.  Noting that ASP.NET validation is far beyond Windows Forms, I thought it might also be a good opportunity to use extension methods.

Sadly, extension methods aren't supported by the C# 2.0 compiler (which I was using, part of Visual Studio 2005), nor are they supported by the .NET Framework 2.0.  So, I wouldn't get IntelliSense support, and it wouldn't build in VS 2005.  But I was curious, and since 2008 supports targeting the 2.0 framework, I thought I'd give it a shot.

So I cranked open 2008 and created a quick test project.  Building out the method: 

   1:  public static class ExtensionMethods
   2:  {
   3:      public static void ValidateMe(this Form form)
   4:      {
   5:          form.ValidateChildren(ValidationConstraints.Enabled);
   6:      }
   7:  }

I get a compiler error:

error CS1110: 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?

So it appeared I would need to link to the 3.5 libraries... or would I? 

   1:  namespace System.Runtime.CompilerServices
   2:  {
   3:      [AttributeUsage(AttributeTargets.Method)]
   4:      public sealed class ExtensionAttribute : Attribute
   5:      {
   6:          public ExtensionAttribute() { }
   7:      }
   8:  }

Lo and behold, it compiled correctly.  Then it worked correctly!

net20Extension

(Note: I wouldn't really make a library with a function called "ValidateMe".  Never!)

Posted on Thursday, December 20, 2007 2:31 PM | Back to top


Comments on this post: Using Extension Methods in .NET 2.0 with Visual Studio 2008

# re: Using Extension Methods in .NET 2.0 with Visual Studio 2008
Requesting Gravatar...
You are about 7 months late discovering this (see my blog) ;-)

Just wanted to make a note that the product teams are not supporting this. Also note that for the other language features you really need SP1 and not RTM of v2.0 on the deployment machine.
Left by Daniel Moth on Dec 21, 2007 1:58 AM

# re: Using Extension Methods in .NET 2.0 with Visual Studio 2008
Requesting Gravatar...
Thanks! it really help
Left by Rafael on Aug 26, 2010 11:51 PM

# re: Using Extension Methods in .NET 2.0 with Visual Studio 2008
Requesting Gravatar...
thx bro ;)
Left by zency on Feb 01, 2012 1:21 PM

Your comment:
 (will show your gravatar)


Copyright © Robert Paveza | Powered by: GeeksWithBlogs.net | Join free