Does anyone know why the last one doesn’t work?
object nullObj = null;
short works1 = (short) (nullObj ?? (short) 0);
short works2 = (short) (nullObj ?? default(short));
short works3 = 0;
short wontWork = (short) (nullObj ?? 0); //Throws: Specified cast is not valid
Because
0is an int, which is implicitly converted to an object (boxed), and you can’t unbox a boxed int directly to a short. This will work:A boxed
T(whereTis a non-nullable value type, of course) may be unboxed only toTorT?.