Consider the MSIL code generated for the following general method:
public static U BoxValue<T, U>(T value)
where T : struct, U
where U : class
{
return value;
}
Appearance:
.method public hidebysig static !!U BoxValue<valuetype .ctor
([mscorlib]System.ValueType, !!U) T,class U>(!!T 'value') cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: box !!T
IL_0006: unbox.any !!U
IL_000b: ret
}
But for the general code above, a more efficient representation of IL should be:
IL_0000: ldarg.0
IL_0001: box !!T
IL_0006: ret
From restrictions it is known that the value is inserted into the reference type. The operation code is Unbox.anycompletely redundant, because after boxthe operation code the value in the IL stack will already be a valid reference to !!Uthat can be used without any unboxing.
Why doesn't the C # 3.0 compiler use restriction metadata to generate more efficient generic code? Unbox.any gives you a little overhead (just 4x5x slower), but why not fix the best code in this scenario?