I'm investigating the execution of this C# code:
public static void Test<T>(object o) where T : class
{
T t = o as T;
}
The equivalent IL code is:
.method public static void Test<class T>(object A_0) cil managed
{
// Code size 13 (0xd)
.maxstack 1
.locals init (!!T V_0)
IL_0000: ldarg.0
IL_0001: isinst !!T
IL_0006: unbox.any !!T
IL_000b: stloc.0
IL_000c: ret
} // end of method DemoType::Test
Based on this answer (unnecessary unbox_any), can anyone explain to me what the exact logic the Jitter is doing here; how exactly does the Jitter decide to ignore the 'unbox_any' instruction in this specific case (theoretically, according to msdn, a NullReferenceException should be thrown when the isinst instruction yields null, but this doesn't happen in practice!)
Update
Based on usr answer and Hans comment, if the obj is a reference type, castclass
will be called, and therefore, no NRE.
But what about the following case?
static void Test<T>(object o) where T : new()
{
var nullable = o as int?;
if (nullable != null)
//do something
}
Test<int?>(null);
And the equivalent IL code (partial):
IL_0001: ldarg.0
IL_0002: isinst valuetype [mscorlib]System.Nullable`1<int32>
IL_0007: unbox.any valuetype [mscorlib]System.Nullable`1<int32>
IL_000c: stloc.0
IL_000d: ldloca.s nullable
IL_000f: call instance bool valuetype [mscorlib]System.Nullable`1<int32>::get_HasValue()
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_0024
In this case its value type so why NRE not thrown?