20

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?

James
  • 7,343
  • 9
  • 46
  • 82

2 Answers2

37

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.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • I tried this before, but it returns the error: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and ''. – James Oct 06 '11 at 02:51
  • 2
    @James: see the cast to `DateTime?` - unfortunately its necessary because both terms must be implicitly convertible - an alternative is `? temp : (DateTime?)null;` – BrokenGlass Oct 06 '11 at 02:53
  • @James, let's look at this. You have to declare the `temp` variable still, so add that line. So we've taken 3 lines of your code down to 2. Is this version more or less readable? We have to scroll to see it all. More or less complex? We've introduced a cast. Half a dozen in one hand, 6 in the other, if you ask me. – Anthony Pegram Oct 06 '11 at 02:56
  • I've just thought - how about `DateTime? whatIActuallyWant = null; try { whatIActuallyWant = Convert.ToDateTime(txtDate.Text); } catch { }` – James Oct 06 '11 at 09:58
  • 3
    @James: I would not go that route - if you expect your parsing might fail use `TryParse` - in any case an exception thrown is very costly at run time, I would try to avoid that. – BrokenGlass Oct 06 '11 at 12:38
  • why doesn't this work with Boolean.Parse...I have to add 2-3 extra lines. – matthewbaskey Mar 03 '16 at 15:18
16

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();
Phil Wright
  • 22,580
  • 14
  • 83
  • 137