ternary operator reports conversion error with nullable types - by dvboom

Status : 

  By Design<br /><br />
		The product team believes this item works according to its intended design.<br /><br />
		A more detailed explanation for the resolution of this particular item may have been provided in the comments section.

Sign in
to vote
ID 341263 Comments
Status Closed Workarounds
Type Bug Repros 1
Opened 4/30/2008 8:32:47 AM
Access Restriction Public


Using the ternary (if-then-else) operator fails when attempting to assign a null value to a nullable type.  The following code fails:

bool IsGood = false;
double? DoubleVar = IsGood ? 0 : null;

But the next bit of code, which I expect would be equivalent to the previous code, successfully compiles:

bool IsGood = false;
double? DoubleVar;
if (IsGood)
    DoubleVar = 0;
    DoubleVar = null;
Sign in to post a comment.
Posted by dvboom on 5/14/2008 at 12:00 PM
I read up on lifted operators. I think I understand why the compiler is trying to evaluate the type of this expression, to ensure that it's not assigning something invalid to the assigned variable. However, this is still an unintuitive and unexpected result. You and I know that this kind of assignment could be verified. We can see that both 0 and null are appropriate values to assign to such a nullable variable. The fact that the compiler can't tell is a limitation. So my request perhaps should have been phrased differently.

The ternary operator should be a lifted operator.

Either that, or any instance of a ternary operator should be converted into the equivalent if-then-else pattern, which would also work (though not sure what side effects that might cause, if any).

How feasible are either of these options? What is the difficulty?
Posted by Microsoft on 5/8/2008 at 3:00 PM

Thanks for your input. We've looked into it and we think the behavior is by design. To determine the type of this expression

IsGood ? 0 : null;

the compiler compares the types of the expressions on each side of : (see section 7.13 of the spec). For the purpose of that comparison the type of 0 is int. Hence the error message.

The reason for 0 to be int and not int? is that the ternary operator is not a lifted operator (see list of lifter operators in section 7.2.7).

Please let me know if you agree/disagree with the analysis.

Marcelo Guerra
C# Compiler QA

Posted by Microsoft on 4/30/2008 at 10:43 PM
Thanks for your feedback.

We are escalating this issue to the appropriate group within the Visual Studio Product Team for triage and resolution.
These specialized experts will follow-up with your issue.

Thank you,
Visual Studio Product Team