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 0
is 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:
short s = (short)(int)(nullObj ?? 0);
A boxed T
(where T
is a non-nullable value type, of course) may be unboxed only to T
or T?
.
The result of the null-coalescing operator in the last line is a boxed int
. You're then trying to unbox that to short
, which fails at execution time in the way you've shown.
It's like you've done this:
object x = 0;
short s = (short) x;
The presence of the null-coalescing operator is a bit of a red-herring here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With