This is a contrived example:
public static class MyExtensions
{
public static void MyMethod( this MyInterface obj, string txt )
{
}
}
interface MyInterface {}
public MyDerived : MyInterface
{
void DoStuff()
{
MyMethod( "test" ); // fails; compiler can't find MyMethod?
}
}
In my example above, I'm trying to call an extension method assigned to an interface from my derived class. The compiler fails here and says that MyMethod does not exist in the current context. I have all the appropriate using statements in my CS file, so I'm not sure what is going on.
C/Invoke is a library for connecting to C libraries at runtime. This differs from the typical method of interfacing with C, which involves writing static definitions which are then compiled to a machine-dependant format.
When a method is invoked (called), a request is made to perform some action, such as setting a value, printing statements, returning an answer, etc. The code to invoke the method contains the name of the method to be executed and any needed data that the receiving method requires.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. The C standard library provides numerous built-in functions that your program can call.
Try invoking it like this
:
this.MyMethod("test");
Here is alternate solution (preferred by me):
(this as MyInterface).MyMethod("test");
Why? - because the solution provided previously will not work in cases when extension method calls class's "new" method (property is a method too). In such cases you may intend to call an extension method on the type declared by the base class/interface, which might behave differently from the derived class/interface.
Also, this solution will work for both "new" and "override" methods, because virtual "override" will anyway invoke derived version, which would be also intended.
EDIT: this may be irrelevant if you don't really want to pass "base" to the extension method and instead allow it take "this". However, you must consider behavioral differences.
Also, interesting to note as an answer to the comment by Darin Dimitrov: extension methods don't require instance to run them, because they are static methods. You can invoke an extension method as static by passing parameters to it. However, "base" is not a valid parameter value for parameter marked with "this" in the extension method declaration, which (if I were MS), would allow to simplify general usage of extension 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