TryParse for Nullable Types

In my last post, I discussed creating a static class for Parsing nullable types.

However, 2.0 also introducing a new TryParse() pattern so that developers would not have to rely on catching exceptions when attempting a Parse() method.  For example: https://msdn.microsoft.com/en-us/library/ch92fbc1.aspx

We can incorporate the TryParse pattern into our NullableParser class as well so that our consuming code to look something like this:

    DateTime? defaultDate = DateTime.Now;
    NullableParser.TryParseNullableDateTime(s, out defaultDate);
    person.DateOfBirth = defaultDate;

Internally, we can implement this the same way as the ParseXXX() methods by leveraging delegate inference and generics.  First define the delegate:

private delegate bool TryParseDelegate<T>(string s, out T result);

Now define the private generic method:

private static bool TryParseNullable<T>(string s, out Nullable<T> result, TryParseDelegate<T> tryParse) where T : struct
{
    if (string.IsNullOrEmpty(s))
    {
       result = null;
        return true;
    }
    else
    {
        T temp;
        bool success = tryParse(s, out temp);
        result = temp;
        return success;
    }
}

Now each public method is trivial to implement:

public static bool TryParseNullableDateTime(string s, out DateTime? result)
{
    return TryParseNullable<DateTime>(s, out result, DateTime.TryParse);
}

private delegate bool TryParseDelegate<T>(string s, out T result);  
Tweet Post Share Update Email RSS