Try this:
int? x = GetBoolValue() ? 10 : (int?)null;
Basically what is happening is that conditional operator is unable to determine the "return type" of the expression. Since the compiler implictitly decides that 10
is an int
it then decides that the return type of this expression shall be an int
as well. Since an int
cannot be null
(the third operand of the conditional operator) it complains.
By casting the null
to a Nullable
we are telling the compiler explicitly that the return type of this expression shall be a Nullable
. You could have just as easily casted the 10
to int?
as well and had the same effect.