Waheed Waheed - 1 year ago 151
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;

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download