Why doesn’t the conditional operator correctly allow the use of “null” for assignment to nullable types? [duplicate]

This doesn’t work because the compiler will not insert an implicit conversion on both sides at once, and null requires an implicit conversion to become a nullable type.

Instead, you can write

task.ActualEndDate = TextBoxActualEndDate.Text != "" ? 
    DateTime.Parse(TextBoxActualEndDate.Text) : new DateTime?();

This only requires one implicit conversion (DateTime to DateTime?).

Alternatively, you can cast either left side:

task.ActualEndDate = TextBoxActualEndDate.Text != "" ? 
    (DateTime?)DateTime.Parse(TextBoxActualEndDate.Text) : null;

This also requires only one implicit conversion.

Leave a Comment