11

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?

2
  • Are you using Visual Studio 2008 or 2005? Commented Feb 17, 2010 at 13:04
  • 2
    then you're out of luck. Commented Feb 17, 2010 at 13:13

2 Answers 2

18

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok thanks, so it looks possible with VS2008 and 2.0, but not VS2005 and 2.0, thanks!
3

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.

2 Comments

@Andreas What, if you use the C# 3.0 compiler? That is definitely cheating.
but possible ... so your answer is wrong. it would be true if it states it is not possible using .net 2.0 compiler

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.