Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null coalescing operator giving Specified cast is not valid int to short

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
like image 644
MatteKarla Avatar asked Jan 04 '12 14:01

MatteKarla


2 Answers

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?.

like image 144
phoog Avatar answered Sep 28 '22 01:09

phoog


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.

like image 26
Jon Skeet Avatar answered Sep 28 '22 01:09

Jon Skeet