Geeks With Blogs
.Nettuce Code Salad
 public static class TryParseExtensions
    {
        delegate bool TryParseFunc<T>(string input, out T output);
        static readonly ConcurrentDictionary<TypeDelegate> Delegates = new ConcurrentDictionary<TypeDelegate>();
 
        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);
        }
    }
Posted on Tuesday, February 19, 2013 9:28 PM | Back to top


Comments on this post: TryParse Extensions

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Jon Canning | Powered by: GeeksWithBlogs.net