Type of conditional expression cannot be determined because there is no implicit conversion between System.DateTime and null
Asked Answered
P

2

12
DateTime tempDate = calculatesomedatetime();
someDateTimeControl.Value = null; //no issue
someDateTimeControl.Value = (tempDate > DateTime.MinValue)? tempDate : null;

Type of conditional expression cannot be determined because there is no implicit conversion between System.DateTime and null

Line 3 throwing me such error which I don't understand as the comparison is (tempDate > DateTime.MinValue) and null is just value assignment. Why would compiler interpret this as error?

However if I write as below, it has no problem

if(tempDate > DateTime.MinValue)
{
    someDateTimeControl.Value = tempDate;
}else
{
    someDateTimeControl.Value = null;
}
Putrescent answered 3/10, 2017 at 4:13 Comment(3)
DateTime is a struct. It cannot be assigned to null. You need to either declare it as nullable (like: DateTime? tempDate = ...) or use some other default value, like DateTime.MinValue.Edvard
@RufusL: Please refer to my line2, the control can accept nullPutrescent
Oh, I must have misread it initially, but the issue is still basically the same. The ternary operator infers the type being returned by the first part, which is a DateTime. You still need to either define tempDate as nullable, or cast it to nullable in the ternary expression.Edvard
M
44

The issue is with the ternary operation. You're changing the data type from DateTime to a nullable DateTime. Ternary operations require you to return the same data type both before and after the colon. Doing something like this would work:

someDateTimeControl.Value = (tempDate > DateTime.MinValue) ? (DateTime?)tempDate : null;
Mcmillen answered 3/10, 2017 at 4:17 Comment(0)
A
4

Cast both sides to a nullable DateTime, that way it is returning the same type on both sides.

someDateTimeControl.Value = (tempDate > DateTime.MinValue)? (DateTime?)tempDate : (DateTime?)null;
Anguine answered 3/10, 2017 at 4:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.