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:
Finally – if you want to use the extension method inside
MyClass(or a subclass), you need an explicitthis– i.e.This is one of the few cases where
thismatters.