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?
Extension methods are very much like
static
methods with the only difference in it having an attributeCompilerServices.ExtensionAttribute
which helps in identifying it as an Extension method.You can read this
To clarify the above answer... Extension Methods ARE static functions. The additional features in .NET 3.5 allow them to be interpreted as if they are new methods on the type in question.
Yes, extension methods are just static methods. They have no extra privileges with respect to the classes they supposedly "extend". However, the compiler does mark the "extension" static method with an ExtensionAttribute. You can see this in the IL. This makes the compiler treat it specially, so that you cannot actually invoke it as a regular static method. For instance, this won't compile:
Even though this is what happens under the hood.
But as LukeH notes below, you can invoke it on the class where it's actually defined... Silly me.
I dont think that
reflection
is involved in extension methods. The extension method is handled in the same way like you write astatic helper function
in ahelper class
, the only difference is that compiler does it for you.Extension methods are just static methods. The only difference is brought by tools such as the Visual Studio editor which pop them up for the auto complete (intellisense) feature. You can find a detailed explanation here: C# Extension Methods: Syntactic Sugar or Useful Tool?
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
And here is the IL code.
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.