Thursday, January 26, 2012

c# : Nullable DateTime


So there I was trying to convert a nullable date time "DateTime?" to DateTime.

Then I got the error:

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

stackoverflow to the rescue and you need to use the null-coalescing operator.

So the code ended up like:
DateTime x = DateTime y ?? DateTime.Now;
Love those "??".

Aside: When I tried to find the article again for this blog, found that searching Google for "??" is an interesting exercise.

Enjoy!