How the C# compiler implement extension methods?
The process is exactly the same as overload resolution:
Func(myObject);
The compiler checks all functions named "Func" and tries to match the static type of myObject to the parametrs (possibly using conversions, upcasting to base class). If it succeeds, then calls the appropriate function.
If you realize that you can call extensions methods "in a normal way", then it clears up:
static class MyExtensions
{
public static void MyFunc(this string arg)
{
// ...
}
}
string a = "aa";
MyExtensions.MyFunc(a); // OK
a.MyFunc(); // same as above, but nicer
For the given type (here string), the compiler just looks for all static functions with "this" modifier on the first argument and tries to match the static type on the left of the . (in this example "a") with the parameter type in the function.
Instance methods of a class have a hidden argument. An example:
class Example {
public void Foo(int arg) {}
}
actually looks like this when the JIT compiler is done with it, converted back to C# syntax:
static void Foo(Example this, int arg) {}
That hidden argument is the reason that you can use this in an instance method. The JIT compiler figures out the argument to pass from the object reference you provide to call the Foo method.
As you can tell, it is now a very short hop to an extension method.
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