Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a static class extension be inlined?

Tags:

c#

.net

clr

jit

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?

like image 263
Meirion Hughes Avatar asked Mar 17 '15 22:03

Meirion Hughes


People also ask

Can we write extension method for static class?

No. Extension methods require an instance of an object.

Can a static class be extended in C#?

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.

Why do extension methods need to be in a static class?

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.

Can extension methods extend non static classes?

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.


1 Answers

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.

like image 104
Erik Avatar answered Oct 13 '22 17:10

Erik