Originally posted on: http://geekswithblogs.net/Nettuce/archive/2013/02/19/tryparse-extensions.aspx
public static class TryParseExtensions { delegate bool TryParseFunc<T>(string input, out T output); static readonly ConcurrentDictionary<Type, Delegate> Delegates = new ConcurrentDictionary<Type, Delegate>(); static TryParseExtensions() { CacheTryParseFor<bool>(bool.TryParse); CacheTryParseFor<byte>(byte.TryParse); CacheTryParseFor<DateTime>(DateTime.TryParse); CacheTryParseFor<decimal>(decimal.TryParse); CacheTryParseFor<double>(double.TryParse); CacheTryParseFor<Int16>(Int16.TryParse); CacheTryParseFor<Int32>(Int32.TryParse); CacheTryParseFor<Int64>(Int64.TryParse); CacheTryParseFor<Single>(Single.TryParse); } public static bool Is<T>(this string s) { return TryParse<T>(s).Item1; } public static T As<T>(this string s) { return TryParse<T>(s).Item2; } static Tuple<bool, T> TryParse<T>(string s) { var dlg = Delegates[typeof(T)] as TryParseFunc<T>; T value; var result = dlg(s, out value); return new Tuple<bool, T>(result, value); } static void CacheTryParseFor<T>(TryParseFunc<T> tryParseFunc) { Delegates.TryAdd(typeof(T), tryParseFunc); } }