Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

If your going to be performing this operation more than once then I recommend adding a simple extension method for ease of use...

public static class Extensions
{
    public static DateTime? ToDateTime(this string val)
    {
        DateTime temp;
        if (DateTime.TryParse(val, out temp))
            return temp;
        else 
            return null;
    }
}

Which you can then use very easily...

DateTime? ret1 = "01/01/2011".ToDateTime();
DateTime? ret2 = myString.ToDateTime();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top