From the MSDN documentation, the following two snippets are equal:
bool value;
int x = (value) ? 0 : 1;
And
bool value;
int x;
if (value)
x = 0;
else
x = 1;
Great, wonderful. I use it all the time. Terse and effective.
If we try this with a nullable type, like so:
int? x = (value.HasValue) ? value.Value : null;
We get a compile-time error:
The type of conditional expression cannot be determined
because there is no implicit conversion between '{NullableType}' and null.
This compiles fine:
int? value;
int? x;
if (value.HasValue)
x = value.Value;
else
x = null;
So, I understand that the compiler requires an explicit cast in the way of (int?)null
to compile the first statement. What I don't understand is why it is required in that statement, but not the If Else
block.
Best Answer
null
can represent any object-based datatype. You need to castnull
as a datatype so it know what you are talking about.I know, it sounds a bit strange.
To answer the questions in the comments:
Let's walk through the code.
Your
else
statement looks like this:This means you are assigning the value of
null
tox
. This is valid, becausex
is aint?
, which takesnulls
.The difference comes when you have the ternary operator. It says: "assign the value of the operator into
x
". The question (and the reason for your error) is, what datatype is the result of the ternary operator?From your code, you can't be sure, and the compiler throws its hands up.
What datatype is
null
? You are quick to say "well it's aint?
, because the other side is aint
and the result is aint?
". The problem is, what about the following:This is also valid, which means
null
can be used forany object-based datatype
. This is why you have to explicitly castnull
as the type you want to use, because it can be used for anything!Another explanation (and possible more accurate):
int
is not-nullable (it's a structure), wherenull
is. This is why in Habib's answer you can put the cast on either the left or right side.