Alex Rivera | Logout

Why is the C# compiler emitting a callvirt instruction for a GetType() method call?

Asked 2009-05-10T16:56:33.440
29

I am curious to know why this is happening. Please read the code example below and the corresponding IL that was emitted in comments below each section:

using System;

class Program
{
    static void Main()
    {
        Object o = new Object();
        o.GetType();

        // L_0001: newobj instance void [mscorlib]System.Object::.ctor()
        // L_0006: stloc.0 
        // L_0007: ldloc.0 
        // L_0008: callvirt instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()

        new Object().GetType();

        // L_000e: newobj instance void [mscorlib]System.Object::.ctor()
        // L_0013: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
    }
}

Why did the compiler emit a callvirt for the first section but a call for the second section? Is there any reason that the compiler would ever emit a callvirt instruction for a non-virtual method? And if there are cases in which the compiler will emit a callvirt for a non-virtual method does this create problems for type-safety?

Edit
Report

1 Answer

0

I would hazard a guess that it's because the first assigns to a variable, which potentially could contain a downcasted instance of another type that could've overridden GetType (even though we can see it doesn't); the second could never be anything other than Object.

answered 2009-05-10T17:10:07.510

Your Answer