views:

47

answers:

2

So at work I was using an API that we didn't write, and one of the methods took a delegate. For one reason or another, the idea came to me that I have an extension method that fits that signature, so I was wondering if it would work. I was sure it wouldn't but much to my surprise, it did. Allow me to demonstrate:

Say I have these classes:

public interface IMyInterface
{

}

public class MyClass : IMyInterface 
{ 

}

public static class Extensions
{
    public static string FuncMethod(this IMyInterface imy, int x)
    {
        return x.ToString();
    }
}

Now let's say I have a method signature somewhere that looks like this:

    private static void Method(Func<int, string> func)
    {

    }

Now my extension method (looks like it) matches that signature, but we all know that extension methods are just smoke and mirrors, so it really doesn't match that signature. Yet, I can safely do this:

var instance = new MyClass();
Method(instance.FuncMethod);

My question is, how does this work? What does the compiler generate for me to make this acceptable. The actual signature of the Extension method takes an instance of IMyInterface, but the Func doesn't so what's happening here for me behind the scenes?

+3  A: 

Instance methods are implemented as taking hidden this parameter.

When you create an instance delegate from an extension method, the hidden this parameter is passed to the method as the first normal parameter.

Note that this cannot be done with value types.

SLaks
A: 

I don't know exactly what the compiler is doing to allow these scenarios, but the expectations seem reasonable. Perhaps this code sample will help with grappling the concept.

MyClass instance = new MyClass();
Func<int, string> f1 = instance.FuncMethod;
Func<int, string> f2 = (i) => instance.FuncMethod(i);
Func<int, string> f3 = (i) => Extensions.FuncMethod(instance, i);
David B