How to convert DateTime? to DateTime

Waheed picture Waheed · Jul 7, 2009 · Viewed 212.4k times · Source

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

chills42 picture chills42 · Jul 7, 2009

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;