How to convert DateTime? to DateTime

MS already made a method for this, so you dont have to use the null coalescing operator. No difference in functionality, but it is easier for non-experts to get what is happening at a glance.

DateTime updatedTime = _objHotelPackageOrder.UpdatedDate.GetValueOrDefault(DateTime.Now);

You can use a simple cast:

DateTime dtValue = (DateTime) dtNullAbleSource;

As Leandro Tupone said, you have to check if the var is null before


Try this

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

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;

Tags:

C#

.Net

Datetime