views:

3904

answers:

6

I want to convert null able datetime "DateTime?" to DateTime. But i am getting error. I have done this like following:

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

But i am getting error:

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

Any help??

+4  A: 

You need to call the Value property of the nullable DateTime. This will return a DateTime.

Assuming that UpdatedDate is DateTime?, then this should work:

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

To make the code a bit easier to read, you could use the HasValue property instead of the null check:

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate.HasValue
                          ? _objHotelPackageOrder.UpdatedDate.Value
                          : DateTime.Now;

This can be then made even more concise:

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;
adrianbanks
+1 for Value - and for null coalescing.
Jeremy McGee
A: 

Try this:

DateTime UpdatedTime = (DateTime)_objHotelPackageOrder.UpdatedDate == null ? DateTime.Now : _objHotelPackageOrder.UpdatedDate.Value;
Tim S. Van Haren
+4  A: 

How about the following:

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate.HasValue ? _objHotelPackageOrder.UpdatedDate.value : DateTime.Now;
Simon Wilson
+27  A: 

Try this

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;
Valentin Vasiliev
+29  A: 

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;
chills42
+1 for the link to null-coalescing operator. Good luck to a novice developer trying to search for '??' on the web.
Matt Howells
+9  A: 

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);
Josh
See, now that's what I'm talkin' about... +1
Christopher Karper
Way more readable than the other options.
Newbie