Extension Methods in Dot Net 2.0
- by Tom Hines
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:
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();
}
}
}
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);
}
};
}