I have this code :
private MyClass CreateObject(MyOtherClass myOtherClass)
{
return new MyClass
{
Name = myOtherClass.Name,
ValidationDate = (DateTime)myOtherClass.ValidationDate //ValidationDate is nullable
};
}
If I do this, I have a compilation error :
Type of conditional expression cannot be determined because there is
no implicit conversion between'<null>'and'System.DateTime'
private MyClass CreateObject(MyOtherClass myOtherClass)
{
return new MyClass
{
Name = myOtherClass.Name,
ValidationDate = (myOtherClass.VALIDATION_DATE == null) ? null : DateTime.Now //ValidationDate is nullable
};
}
If I do this, no problem :
MyClass myClass = new MyClass();
if (myClass.ValidationDate == null)
myClass.ValidationDate = null;
The question is why ? and Solustion ? 🙂
The problem in the first code block is that you’re trying to cast a nullable DateTime value to DateTime.
Try casting it to nullable DateTime (
DateTime?) instead:because you’re trying to populate a nullable DateTime field after all.
If you’re trying to provide a default value in case
myOtherClass.ValidationDateis null, then use the coalescing operator (no casts needed):