Sergio
Sergio

Reputation: 8259

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?

Upvotes: 5

Views: 1876

Answers (4)

Matthias Meid
Matthias Meid

Reputation: 12523

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

using Myself.MyProduct.MyNamespace;

Upvotes: 5

Dan McClain
Dan McClain

Reputation: 11920

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

Upvotes: 6

Ben S
Ben S

Reputation: 69342

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.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062865

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.

Upvotes: 19

Related Questions