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?
To answer on the second case (update section on the question) of nullable value type, we need to look closely in the ECMA CLI spec (III.4.33 unbox.any – convert boxed type to value):
The bold part is missing from the MSDN documentation.
So to summarize the behavior of unbox_any:
If typeTok is a value type:
2.1. If obj is null and typeTok is a nullable value type, the result is null
2.2. If obj is null and typeTok is not a nullable value type, a NullReferenceException will thrown
If I understand correctly, the behavior of paragraph 2.2 is same as regular unbox operation see jitter source code
T
is constrained to be a reference type. This instruction does not throw a NRE in this case. The JIT does not "ignore" it, it executes it as specified. The JIT is not allowed to ignore instructions.The documentation has the statement
which is misleading as it only applies to value types. The first statement that I quoted is unambiguous.