How are extension methods implemented internally? I mean what happens when the compiler sees a declaration for an extension method and what happens at runtime when there is a call to an extension method.
Is reflection involved? Or when you have an extension method is its code injected in the target class type metadata with some additional flags noting that this is an extension method and then the CLR knows how to handle that?
So in general, what happens under the hood?
As explained by Andrey himself, the extension functions are nothing but regular static functions which takes in an instance of the receiver class as a parameter implicitly when you define the function and operates on that.
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.
As already have said by other colleagues it is just a static method. It is all about the compiler we can say that CLR even have no idea about extension methods. You can try to check IL code ..
Here is an example
static class ExtendedString
{
public static String TestMethod(this String str, String someParam)
{
return someParam;
}
}
static void Main(string[] args)
{
String str = String.Empty;
Console.WriteLine(str.TestMethod("Hello World!!"));
........
}
And here is the IL code.
IL_0001: ldsfld string [mscorlib]System.String::Empty
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldstr "Hello World!!"
IL_000d: call string StringPooling.ExtendedString::TestMethod(string,
string)
IL_0012: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: nop
As you can see it is just a call of static method. The method is not added to the class, but compiler makes it look like that. And on reflection layer the only difference you can see is that CompilerServices.ExtensionAttribute is added.
extension methods are converted to static functions.In other words,They are syntactic sugar for static functions.
I dont think that reflection
is involved in extension methods. The extension method is handled in the same way like you write a static helper function
in a helper class
, the only difference is that compiler does it for you.
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