I am studying the execution of this C # code:
public static void Test<T>(object o) where T : class { T t = o as T; }
Equivalent IL code:
.method public static void Test<class T>(object A_0) cil managed {
Based on this answer ( unnecessary unbox_any ), can anyone explain to me what the exact logic that Jitter does here is; how exactly the jitter decided to ignore the "unbox_any" instruction in this particular case (theoretically, according to MSDN, a NullReferenceException should be thrown when the isinst instruction gives null, but this does not happen in practice!)
Update
Based on usr's answer and Hans's comment, if 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)
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 type value is so why NRE is not thrown?
source share