HomeContact

Generic TryParse, convert string to any type

I came up with this nifty little extension method today. This method works in a similar fashion to TryParse but you can pass in any type. You may want to throw an exception if converter == null, as that means there is no converter available for the specified type.

    using System.ComponentModel;
...

    public static bool GenericTryParse<T>(this string input, out T value)
    {
        var converter = TypeDescriptor.GetConverter(typeof(T));
 
        if (converter != null && converter.IsValid(input))
        {
            value = (T)converter.ConvertFromString(input);
            return true;
        }
        value = default(T);
        return false;
    }

Scott HanselmanĀ has a post that talks more about TypeDescriptor.GetConverter and how to roll your own converters. Also read the comments on that post for some potential gotchas with using TypeConverters.


Home
Improve Your Life
Improve Your Team
Improve Your Code
Opinion
Software Projects

David Walker

David Walker is a Secure Software Consultant, a Certified Secure Software Lifecycle Professional (CSSLP), and a Certified Scrum Leader. He believes in secure and reliable software and productive happy teams. He lives in Orlando with his lovely wife Lynn and his 2 dogs.