I have a string representing a date time, and a datetime local variable property. The string representing the datetime could be null or an empty string. To check for this, I thought I could check for a null or whitespace value and assign the appropriate value using this code:
ReturnValue.ArrivalDate = string.IsNullOrWhiteSpace(Screenings.ArrivalDate) ? null : DateTime.Parse(Screenings.ArrivalDate);
Pretty simple. The property ReturnValue.ArrivalDate
is of the type DateTime?
. So if the Screenings.ArrivalDate
string is null or white space, it would assign the value null
to the nullable ReturnValue.ArrivalDate
property and if it's not null or whitespace, it would parse the string and return a DateTime object.
This line of code though produces this error:
Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'DateTime'
The following code block though does work, it just looks horrible:
if (!string.IsNullOrWhiteSpace(Screenings.ArrivalDate))
{
ReturnValue.ArrivalDate = DateTime.Parse(Screenings.ArrivalDate);
}
else
{
ReturnValue.ArrivalDate = null;
}
Why does the ugly if/else work, but the nice single line (which, I would imagine compiles the same as the above if/else) is failing?