Question

C# 3 brought us extension methods.

However, other languages such as VB.NET also implement extension methods by way of specifying an attribute declaration on top of a method which has to be declared in a VB.NET module.

Also, you can use extension methods in C++/CLI.

So, I am wondering if extension methods are a language feature or a feature that's built into the CLR?

I am guessing it is a compiler trick since you can even invoke them as plain static methods of the types they are declared within and therefore must be a language specific feature (and must have been implemented by Microsoft in VB.NET, C# and C++ extensions only for the sake of uniformity, but are not necessary for any other language that wants to target the CLR) but I couldn't be sure.

Was it helpful?

Solution

They are a language extension. As you suspected, the compiler is doing all the work and producing IL code that calls the extension method explicitly as a static method. This can be verified by looking at the IL.

IL_0000:  newobj     instance void Sandbox.Program/Foo::.ctor()
IL_0005:  stloc.0
IL_0006:  ldloc.0
IL_0007:  call       void Sandbox.Program::Bar(class Sandbox.Program/Foo)

Here I defined a class Foo and an extension method Bar() and then called foo.Bar().

The dump of the Bar() function shows it doesn't do anything special, except for the System.Runtime.CompilerServices.ExtensionAttribute:

.method public hidebysig static void Bar(class Sandbox.Program/Foo foo) cil managed
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) 
  // Code size       1 (0x1)
  .maxstack  8
  IL_0000:  ret
} // end of method Program::Bar
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top