سؤال

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top