Skip to main content
1 of 2
Nick Udell
  • 5.2k
  • 1
  • 28
  • 68

If you're doing this a lot, you could consider a custom method for it:

public static DateTime TryParse(object from, Func<DateTime> failureResult)
{
    DateTime result;
    if (!DateTime.TryParse(from, out result))
    {
        result = failureResult();
    }
    return result;
}

Or (for when you're not accessing time-sensitive DateTime values (i.e. not DateTime.Now()):

public static DateTime TryParse(object from, DateTime failureResult)
{
    DateTime result;
    if (!DateTime.TryParse(from, out result))
    {
        result = failureResult;
    }
    return result;
}

This calls the failureResult delegate that will return your DateTime if DateTime's TryParse fails.

Your usage would be:

dateFrom = TryParse(txtDateFrom.Text, ()=>DateTime.Today.AddDays(-7));
dateTo = TryParse(txtDateTo.Text, ()=> DateTime.Now);

Or with the second snippet:

dateFrom = TryParse(txtDateFrom.Text, DateTime.Today.AddDays(-7));
dateTo = TryParse(txtDateTo.Text, DateTime.Now);

Sadly you cannot make a static extension method so this will have to exist somewhere else (although you could make it an extension of string).

Nick Udell
  • 5.2k
  • 1
  • 28
  • 68