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?
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.
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
Did you import (using
clause at the beginning) the namespace in which Extensions
class is?
using Myself.MyProduct.MyNamespace;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With