C# – How to convert DateTime? to DateTime


I want to convert a nullable DateTime (DateTime?) to a DateTime, but I am getting an error:

Cannot implicitly convert type 'System.DateTime?' to
'System.DateTime'. An explicit conversion exists (are you missing a

I have attempted the following:

DateTime UpdatedTime = (DateTime)_objHotelPackageOrder.UpdatedDate == null 
    ? DateTime.Now : _objHotelPackageOrder.UpdatedDate;

Best Solution

You want to use the null-coalescing operator, which is designed for exactly this purpose.

Using it you end up with this code.

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;