TryParse to a nullable type

James picture James · Oct 6, 2011 · Viewed 11.6k times · Source

I would like to try to parse a string as a DateTime?, and if it fails then set the value to null. The only way I can think to do this is the following, but it doesn't seem very neat.

DateTime temp;
DateTime? whatIActuallyWant = null;
if (DateTime.TryParse(txtDate.Text, out temp)) whatIActuallyWant = temp;

Is this the only way?

Answer

BrokenGlass picture BrokenGlass · Oct 6, 2011

How about this:

DateTime? whatIActuallyWant = DateTime.TryParse(txtDate.Text, out temp) ? (DateTime?)temp : null;

You get a one-liner out of this (unfortunately need the DateTime? cast otherwise won't compile) - but personally I would probably stick to the null initialization and the subsequent if - it's just easier to read.