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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With