A small problem. Any idea guys why this does not work?
int? nullableIntVal = (this.Policy == null) ? null : 1;
I am trying to return null
Yes - the compiler can't find an appropriate type for the conditional expression. Ignore the fact that you're assigning it to an int?
- the compiler doesn't use that information. So the expression is:
(this.Policy == null) ? null : 1;
What's the type of this expression? The language specification states that it has to be either the type of the second operand or that of the third operand. null
has no type, so it would have to be int
(the type of the third operand) - but there's no conversion from null
to int
, so it fails.
Cast either of the operands to int?
and it will work, or use another way of expessing the null value - so any of these:
(this.Policy == null) ? (int?) null : 1;
(this.Policy == null) ? null : (int?) 1;
(this.Policy == null) ? default(int?) : 1;
(this.Policy == null) ? new int?() : 1;
I agree it's a slight pain that you have to do this.
From the C# 3.0 language specification section 7.13:
The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,
If X and Y are the same type, then this is the type of the conditional expression.
Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
Otherwise, no expression type can be determined, and a compile-time error occurs.