In my last post, I discussed creating a static class for Parsing nullable types:
http://geekswithblogs.net/michelotti/archive/2006/01/16/66014.aspx
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:
http://msdn2.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:
1: 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);