views:

423

answers:

2

I want to do this, but getting this error:

Error 1 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? [snipped some path stuff]

I have seen some answers here that says, you have to define this attribute yourself.

How do I do that?

EDIT: This is what I have:

[AttributeUsage ( AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method )]
public sealed class ExtensionAttribute : Attribute
{
 public static int MeasureDisplayStringWidth ( this Graphics graphics, string text )
 {

 }
}
+13  A: 

Like so:

// you need this once (only), and it must be in this namespace
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class
         | AttributeTargets.Method)]
    public sealed class ExtensionAttribute : Attribute {}
}
// you can have as many of these as you like, in any namespaces
public static class MyExtensionMethods {
    public static int MeasureDisplayStringWidth (
            this Graphics graphics, string text )
    {
           /* ... */
    }
}

Alternatively; just add a reference to LINQBridge.

Marc Gravell
Thanks Marc, it was actually your post that I read. I just tried but got this: Error 1 Extension methods must be defined in a non-generic static class, where I have a method like this: public static int MeasureDisplayStringWidth ( this Graphics graphics, ... )
Joan Venge
Also ExtensionAttribute can be any name, right? And why inherit from Attribute?
Joan Venge
You need to inherit from Attribute for it to be an attribute... and it needs to be called ExtensionAttribute so the compiler can find it. (That's what it expects it to be called.) Your error is probably that it's not in a static class.
Jon Skeet
Thanks Jon, I see what you mean. Now this is what I don't understand. Where does my extension class method goes? Does the class go inside this ExtensionAttribute with my method?
Joan Venge
I added my code to the question.
Joan Venge
+3  A: 

Follow the directions here: Extension Methods in .NET 2.0

Justin Niessner