What's the point of MethodImplOptions.InternalCall?

Ani picture Ani · Jun 22, 2012 · Viewed 11k times · Source

Many methods in the BCL are marked with the [MethodImpl(MethodImplOptions.InternalCall)] attribute. This indicates that the "method is implemented within the common language runtime itself".

What was the point of designing the framework in this way over having specified explicit CIL instructions that the runtime would be forced to implement? Ultimately, the attribute is creating contractual obligations for the runtime, but in a way that appears to me to be confusing and not immediately obvious.

For example, Math.Pow could have been written this way (excuse my informal mixture of C# + IL and the IL itself if it is bad; this is only a sample to explain my point):

public static double Pow(double x, double y)
{
    ldarg.0
    ldarg.1
    pow // Dedicated CIL instruction
    ret
}

instead of the current way:

[MethodImpl(MethodImplOptions.InternalCall)]
public static double Pow(double x, double y);

Why does MethodImplOptions.InternalCall exist?

Answer

svick picture svick · Jun 22, 2012

I think a big reason is that it's quite hard to create a new IL instruction and it could affect a lot of tools, including external ones (ILGenerator, ilasm, ildasm, PEVerify, Reflector, PostSharp, …).

But creating a new InternalCall method? That's almost as simple as writing the method in C# (I assume, I didn't look at Rotor to verify) and it doesn't affect anything.

And it's not just about creating it, I think the same applies to maintenance.