Skip to content

Instantly share code, notes, and snippets.

@cliss
Last active October 11, 2015 07:07
Show Gist options
  • Save cliss/3821562 to your computer and use it in GitHub Desktop.
Save cliss/3821562 to your computer and use it in GitHub Desktop.
ParseOrDefault<T>
#region Fields
private static Dictionary<Type, MethodInfo> _tryParseMethods = new Dictionary<Type, MethodInfo>();
#endregion Fields
#region Methods
/// <summary>
/// Invokes a TryParse(string, out T) method on the given input.
/// If that invocation returns <c>false</c>, or the method does
/// not exist, then <c>default(T)</c> is returned.
/// </summary>
/// <typeparam name="T">Type to attempt to convert to</typeparam>
/// <param name="input">String to parse</param>
/// <returns>Parsed string, or <c>default(T)</c> if it can't be parsed.</returns>
public static T ParseOrDefault<T>(string input)
{
// If T is actually Nullable<U>, then the type we want is U. Otherwise, take T.
Type t = typeof (T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof (Nullable<>)
? typeof (T).GetGenericArguments()[0]
: typeof (T);
// If it's not cached, cache it.
if (!_tryParseMethods.ContainsKey(t))
{
_tryParseMethods[t] = t.GetMethod("TryParse", new[] {typeof (string), t.MakeByRefType()});
}
// Now do the work.
if (_tryParseMethods[t] != null)
{
object[] parameters = new object[] {input, null};
bool parsed = (bool) _tryParseMethods[t].Invoke(null, parameters);
if (parsed)
{
return (T) parameters[1];
}
}
return default(T);
}
#endregion Methods
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment