mercredi 21 octobre 2015

Different IL codes for same method body

Let's suppose I have the following class:

public class SomeClass
{
    public int GetValue()
    {
        return 1;
    }
}

Inspecting the generated IL code for this method:

byte[] methodBody = typeof(SomeClass).GetMethod("GetValue").GetMethodBody().GetILAsByteArray();

We get that methodBody is:

[0, 23, 10, 43, 0, 6, 42] -- 7 bytes

Creating my own method using Reflection.Emit:

MethodBuilder methodBuilder = typeBuilder.DefineMethod("GetValue", MethodAttributes.Public, typeof(int), Type.EmptyTypes);
ILGenerator il = methodBuilder.GetILGenerator();
il.Emit(OpCodes.Ldc_I4, 1);
il.Emit(OpCodes.Ret);

//....

byte[] dynamicMethodBody = dynamicType.GetMethod("GetValue").GetMethodBody().GetILAsByteArray();

We get that dynamicMethodBody is:

[32, 1, 0, 0, 0, 42] -- 6 bytes

Why are the two method bodies different? Aren't they exactly the same?

Furthermore, I'm guessing the first two bytes 32 and 1 in my dynamicMethodBody have something to do with loading the constant 1 to the evaluation stack, but why aren't these two bytes present in methodBody?





Aucun commentaire:

Enregistrer un commentaire