views:

181

answers:

4

I was wondering if there is a way to create extension methods using Visual Studio 2005 and the 2.0 framework?

public static class StringExtensions
{
    public static void SomeExtension(this String targetString)
    {

    }
}

If there is no way to do this, what would the equivalent be? Just create static methods in some sort of library class?

A: 

this is explained here

Adeel
+2  A: 

No, this isn't possible in .Net 2.0 (without using the C# 3.0 compiler). You can just create static methods that do exactly the same thing however:

public static class StringExtensions
{
    public static void SomeExtension(String targetString)
    {
        // Do things
    }
}

// Example use:
StringExtensions.SomeExtension(targetString);

In reality extension methods are just a shorthand way of writing the above.

Kragen
it **is** possible ...
Andreas Niedermair
@Andreas What, if you use the C# 3.0 compiler? That is *definitely* cheating.
Kragen
but possible ... so your answer is wrong. it would be true if it states `it is not possible using .net 2.0 compiler`
Andreas Niedermair
removed downvote :)
Andreas Niedermair
A: 

ever tried? will give you a

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?

solution found via google here, or here

Andreas Niedermair
-1: requires c# 3.0
John Saunders
nope ... second link: targeting .net 2.0, using 3.0 compiler
Andreas Niedermair
You are making a .Net 2.0 app that requires a C# 3.0 compiler - although interesting that its possible, there is just no way that I would ever want to do this with production code.
Kragen
me neither :) but hey, it's possible!
Andreas Niedermair
@Andreas: no, note the OP says he's using VS2005.
John Saunders
since when are you not able to inject the compiler?
Andreas Niedermair
+13  A: 

You can create extension methods using .Net framework 2.0, if you use the C# 3.0 compiler and Visual Studio 2008 or greater.

The catch is that you have to add this code to your project:

 namespace System.Runtime.CompilerServices
{
  public class ExtensionAttribute : Attribute { }
}

Basically you need to re declare the ExtensionAttribute in Core.dll (.Net 3.5 +), in your project.

Pop Catalin
Ok thanks, so it looks possible with VS2008 and 2.0, but not VS2005 and 2.0, thanks!
DevDemon