Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

expression

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;
}
like image 554
SuicideSheep Avatar asked Oct 03 '17 04:10

SuicideSheep


2 Answers

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;
like image 134
Middas Avatar answered Nov 06 '22 10:11

Middas


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;
like image 3
Tim M Avatar answered Nov 06 '22 12:11

Tim M