Extension Methods in Dot Net 2.0

Posted by Tom Hines on Geeks with Blogs See other posts from Geeks with Blogs or by Tom Hines
Published on Fri, 05 Mar 2010 18:57:45 GMT Indexed on 2010/03/07 23:28 UTC
Read the original article Hit count: 571

Filed under:

Not that anyone would still need this, but in case you have a situation where the code MUST be .NET 2.0 compliant and you want to use a cool feature like Extension methods, there is a way. 

I saw this article when looking for ways to create extension methods in C++, C# and VB:

 http://msdn.microsoft.com/en-us/magazine/cc163317.aspx

The author shows a simple  way to declare/define the ExtensionAttribute so it's available to 2.0 .NET code.

Please read the article to learn about the when and why and use the content below to learn HOW.
In the next post, I'll demonstrate cross-language calling of extension methods.


Here is a version of it in C#

First, here's the project showing there's no VOODOO included:

Picture of Project Workspace

using System;

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

namespace TestTwoDotExtensions
{
   public static class Program
   {
      public static void DoThingCS(this string str)
      {
         Console.WriteLine("2.0\t{0:G}\t2.0", str);
      }

      static void Main(string[] args)
      {
         "asdf".DoThingCS();
      }
   }
}

 

Picture of mouseover showing the Intellisense



Here is the C++ version:

// TestTwoDotExtensions_CPP.h
#pragma once
using
namespace System;

namespace System {
       namespace Runtime {
              namespace CompilerServices {
              [
                     AttributeUsage(
                           AttributeTargets::Assembly
                            | AttributeTargets::Class
                           | AttributeTargets::Method,
                     AllowMultiple = false, Inherited = false)
              ]
              public ref class ExtensionAttribute : Attribute{};
              }
       }
}

using namespace System::Runtime::CompilerServices;

namespace TestTwoDotExtensions_CPP {

public
ref class CTestTwoDotExtensions_CPP
{
   public:
           [ExtensionAttribute] // or [Extension]
           static void DoThingCPP(String^ str)
   {
      Console::WriteLine("2.0\t{0:G}\t2.0", str);
   }
};
}

© Geeks with Blogs or respective owner