I have a tendency (throw back to c++ days) to add inlining hints to small methods, for example:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Add(this IProject @this, IComponent component)
{
@this.Components.Add(component);
}
I was wondering whether a static class extension-methods could be inlined in the first place?
No. Extension methods require an instance of an object.
If you are talking about using the extension method system to extend a static class then no, you cannot. Extension methods require an object (instance of a class) that will be passed in as the (this) parameter to the static method. Static classes cannot be extended in this way, because they are not instances.
It is compulsion that the Extension method must be in a Static class only so that only one Instance is created. For example, if you place the following in ASP.Net page it will not work. Though error will not come, but you will not see the method available. The above will not work.
Actually I'm answering the question of why extension methods cannot work with static classes. The answer is because extension methods are compiled into static methods that cannot recieve a reference to a static class.
Static methods can be inlined. See here for information on how to check if a method is being inlined. Extension methods are no different from normal static methods; in IL they are just decorated with a System.Runtime.CompilerServices.ExtensionAttribute
, so they will be treated the same by the JIT.
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