Update: I must give credit where credit is due. Daniel Moth commented on this post and pointed out that he discovered this quite a while ago. Although if I only posted completely original content, then I probably would only have one or two posts on this blog. :-)
I was at the Richmond .net users group meeting tonight and a comment was made about automatic properties and how if the project was targeting .net 3.5 then we could use them. Well, I later explained that automatic properties, along with extension methods, were just compiler tricks and since in Visual Studio 2008 even if you target the .net framework 2.0 you are still using the C# 3.0 compiler; therefore you can use these features. They don't produce any invalid IL to the .net 2.0 runtime, so they can be used.
Well, I was 100% correct about the automatic properties, but I was only 99% correct about the extension methods. :-) You have to a do a *bit* of work to get it working, but it is a very tiny bit. So, I thought it would be a wonderful blog post, so here it goes...
When I created a .net 2.0 targeted application like this:
And then I try to implement this horribly useless extension method:
public static class ExtensionMethodClass
{
public static string ExtensionMethodTest
(this string value, int start)
{
return value.Substring(start);
}
}
Then I get this error:
I saw this error and I said, hmmmmmm, that is in a .net 3.5. Well lets reflect that attribute anyways. When I did so I got this:
Well, that is easy enough. Lets doooooooooooooooo it!! So I just implemented my own (make sure you fake the namespace):
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Method
| AttributeTargets.Class
| AttributeTargets.Assembly)]
public sealed class ExtensionAttribute : Attribute
{
}
}
Now I compile and run this:
static void Main(string[] args)
{
string test = "Test String!!";
string result = test.ExtensionMethodTest(3);
}
And everything works great! Hopefully you can get some use from this!