Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an extension method to a method expecting a delegate. How does this work?

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?

like image 906
BFree Avatar asked Jul 19 '10 20:07

BFree


People also ask

How does extension method work?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

What are extension methods explain with an example?

An extension method is actually a special kind of static method defined in a static class. To define an extension method, first of all, define a static class. For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example.

How does extension method work in C#?

In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.


1 Answers

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.

like image 59
SLaks Avatar answered Oct 25 '22 03:10

SLaks