Waheed Waheed - 3 months ago 39
C# Question

How to convert DateTime? to DateTime

I want to convert a nullable DateTime (

) to a
, but I am getting an error:

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

I have attempted the following:

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


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;