tags:

views:

107

answers:

3
+4  Q: 

Extension methods

How the c# compiler implements the "extension methods"?

+3  A: 

This might help

http://www.hanselman.com/blog/HowDoExtensionMethodsWorkAndWhyWasANewCLRNotRequired.aspx

Hainesy
Great! Thanks!!
alfdev
+4  A: 

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.

Stefan
+1  A: 

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.

Hans Passant