How are extension methods compiled?
Asked Answered
U

3

9

How the C# compiler implement extension methods?

Unsociable answered 14/10, 2010 at 10:10 Comment(0)
O
6

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.

Oversubtlety answered 14/10, 2010 at 10:18 Comment(0)
S
3

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.

Shockheaded answered 14/10, 2010 at 10:53 Comment(0)
S
0

The compiler first looks in the base class for a function matching the signature of the function. If it can't find it than it looks for an extension. If an extension has the same signature as a base class method than the base class method is called instead.

This might help: Extension Methods

Sudor answered 16/4, 2013 at 3:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.