C
Chris Dunaway
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?
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?