Waheed Waheed - 20 days ago 8
C# Question

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 cast?)"


I have attempted the following:

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

Answer

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;