Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to DateTime nullable variable in one line

Tags:

c#

asp.net

c#-3.0

How can I write

string date = "12/2/2011";

DateTime? dt = date ?? DateTime.Parse(date);

this throws a compile time error. I know I can do tryparse or do if {}. Is there any way to do this in one line?

like image 268
coder net Avatar asked Dec 01 '11 20:12

coder net


2 Answers

Try using the conditional operator ?: instead of the null-coalescing operator ??:

DateTime? dt = date == null ? (DateTime?)null : DateTime.Parse(date);

You also need to cast the null to DateTime? otherwise you will get a compile error.

like image 96
Mark Byers Avatar answered Oct 23 '22 04:10

Mark Byers


string date = "12/2/2011";

DateTime? dt = String.IsNullOrEmpty(date) ? (DateTime?)null : DateTime.Parse(date);
like image 3
AD.Net Avatar answered Oct 23 '22 02:10

AD.Net