Chris,
This is from the C# language specification:
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.
Here are why the conditions don't apply to your example.
- X is null, so there is no type associated with it. You don't have a
cast either saying what this should be a null of.
- There is no conversion from X (null) to Y (DateTime) that is implicit,
so this condition doesn't apply.
- There is no conversion from Y (DateTime) to X (null) which is
implicit, so this condition doesn't apply.
- This condition applies, because no expression type can be determined.
Now, you can get around this one of three ways. The first is to cast
both sides to DateTime?, which would result in condition one being
satisfied. If you cast the null to DateTime?, then condition three is
satisfied, since there is an implicit conversion from DateTime to DateTime?.
If you cast the DateTime to DateTime?, then condition two is satisfied,
since there is an implicit conversion from null to DateTime?.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
-
mv*@spam.guard.caspershouse.com
"Chris Dunaway" <du******@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
Consider this code (.Net 2.0) which uses a nullable type:
private void button1_Click(object sender, System.EventArgs e)
{
DateTime? nullableDate;
nullableDate = (condition) ? null : DateTime.Now;
}
When the condition is false, I want to return null. If true, I want to
return the current date/time.
The compiler error I get is:
Type of conditional expression cannot be determined because there is no
implicit conversion between '<null>' and 'System.DateTime'
Why should it matter if the true and false expressions can be converted
to *each other*? As long as each of the expressions can be assigned to
the result, it should be allowed! Since both null and DateTime.Now can
be assigned to the variable 'nullableDate', I don't understand why the
line is not allowed?
If you refactor this code to this:
if (true != false)
nullableDate = null;
else
nullableDate = DateTime.Now;
It works fine. Why do the true/false parts of the ternary operator
have to have implicit conversions between them? As long as each of
them are assignable to the result variable, it seems to me that it
should work?
Why was it designed this way?