Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are extension methods compiled?

Tags:

c#

.net-3.5

How the C# compiler implement extension methods?

like image 616
alfdev Avatar asked Oct 14 '10 10:10

alfdev


2 Answers

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.

like image 151
Stefan Avatar answered Nov 01 '22 17:11

Stefan


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.

like image 42
Hans Passant Avatar answered Nov 01 '22 17:11

Hans Passant