Member-only story
Using Ternary operations with nullable DateTime and null in C#
Type of conditional expression cannot be determined because there is no implicit conversion between between ‘<null>’ and ‘System.DateTime’
This post explains how to fix the error in the title when using a Ternary operation on a nullable DateTime variable with null as a possible outcome in C#.
Background
For a project I was working on, I had some nullable DateTime properties that I needed to set in my business logic. To keep things simple, I’ll show a simplified example of a class with a nullable DateTime property:
Public Class MyClass
{
private DateTime? StartDate {get; set;}
}
Use-Case
As I wanted to be able to set its value depending on some business logistics I tried setting it using a Ternary operation. Just to keep my code mean and lean on this part:
var myInstance = new Myclass();
...
myInstance.StartDate =…