A small problem. Any idea guys why this does not work?
int? nullableIntVal = (this.Policy == null) ? null : 1;
I am trying to return null if the left hand expression is True, else 1. Seems simple but gives compilation error.
Type of conditional expression cannot be determined because there is no implicit conversion between null and int.
If I replace the null in ? null : 1 with any valid int, then there is no problem.
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: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.
nullhas no type, so it would have to beint(the type of the third operand) – but there’s no conversion fromnulltoint, 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:I agree it’s a slight pain that you have to do this.
From the C# 3.0 language specification section 7.13: