Please see here for the
extension method[
^]definition and etc.
Now do bit of interesting work, in this research I use
ILDasm(
C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\ildasm.exe but this is for my installed VS) tool which comes as part of the VS installation. I use the same C# code as OP provided except change the class name
Exte
to
ExtensionMethodClass
.
I build the program and grab the exe of the program in this case it is
ConsoleApplication24.exe
(as I put the code in the console app which is called ConsoleApplication24.) into the ILDasm program and ILDasm generate following IL code for the
ExtensionMethodClass
class in here we define the extension method.
.class public abstract auto ansi sealed beforefieldinit ExtensionMethodClass
extends [mscorlib]System.Object
{
.custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor()
.method public hidebysig static string GetFirstThreeCh(string str) cil managed
{
.custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor()
.maxstack 3
.locals init (
[0] string str2,
[1] bool flag)
}
}
If we look into the IL code above, we can see,
ExtensionMethodClass
class has been define as abstract and sealed.
- Inside this class
GetFirstThreeCh
method has been compiled as static public method which has string type parameter. NOTE that in here there is no this which we define in the C# code in the GetFirstThreeCh method.
- So it is clear more this IL code that extension method has been define as same as static method.
Let’s see the usage of this
GetFirstThreeCh
extension method from the Main method which will show us the calling convention of the extension method in underneath. I extracted the following IL code from the program class of the
ConsoleApplication24.exe
program using the ILdasm,
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack 1
.locals init (
[0] string str)
L_0000: nop
L_0001: ldstr "my new String"
L_0006: stloc.0
L_0007: ldloc.0
L_0008: call string ConsoleApplication24.ExtensionMethodClass::GetFirstThreeCh(string)
L_000d: stloc.0
L_000e: ret
}
From the above IL code in L_0008 label we can see that
GetFirstThreeCh
method has been call as same as CLR call static method.
To test this I created a small static class with a static method as below,
namespace ConsoleApplication24
{
class Program
{
static void Main(string[] args)
{
TestStaticMethod.TestMethod();
}
}
public class TestStaticMethod
{
public static void TestMethod()
{
}
}
}
After building this new program I decompiled using ILDasm program to generate the IL code which is as below,
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack 8
L_0000: nop
L_0001: call void ConsoleApplication24.TestStaticMethod::TestMethod()
L_0006: nop
L_0007: ret
}
So we can see that how does CLR handle the extension method in behind the scene.
Hope it explain the details :)