Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler error referencing custom C# extension method

I am trying for the first time to create an extension method and i am having some trouble... maybe you guys can help out :)

public static class Extentions
    {
        public static int myMethod(this MyClass c)
        {
              return 1;
        }
    }

then when i do "MyClass.myMethod" i get q compiler error saying that the method does not exists...

Why is that?

like image 392
Sergio Avatar asked Mar 12 '09 12:03

Sergio


4 Answers

First, you need a "using" directive to include the namespace that includes your class with extension methods.

Second - re "MyClass.myMethod" - extension methods work on instances, not as static - so you'd need:

MyClass foo = ...
int i = foo.myMethod(); // translates as: int i = Extentions.myMethod(foo);

Finally - if you want to use the extension method inside MyClass (or a subclass), you need an explicit this - i.e.

int i = this.myMethod(); // translates as: int i = Extentions.myMethod(this);

This is one of the few cases where this matters.

like image 143
Marc Gravell Avatar answered Oct 01 '22 15:10

Marc Gravell


Did you include the namespace where your extension is defined? I've been burned by that before.

And a way to get around having to add the namespace where your extension is to define the extension in that namespace. This is not a good practice though

like image 30
Dan McClain Avatar answered Oct 01 '22 16:10

Dan McClain


Did you import (using clause at the beginning) the namespace in which Extensionsclass is?

using Myself.MyProduct.MyNamespace;
like image 24
Matthias Meid Avatar answered Oct 01 '22 16:10

Matthias Meid


Is there a reason forcing you to use Extension methods?

You should only be using extension methods if you cannot add the method in the original source and cannot extend the class with a sub-class (if it is declared sealed)

The page on Extension methods states:

In general, we recommend that you implement extension methods sparingly and only when you have to. Whenever possible, client code that must extend an existing type should do so by creating a new type derived from the existing type. For more information, see Inheritance (C# Programming Guide).

Here is even more info regarding classes and polymorphism.

If extending the class is really not a possibility then follow the other answers regarding the using directive and instance methods vs static methods.

like image 26
Ben S Avatar answered Oct 01 '22 16:10

Ben S