David Walker

Generic TryParse, convert string to any type

by David Walker

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.

David Walker

David Walker is a Software Consultant, Photographer, and Digital Artist based out of Orlando, Florida, USA.

He believes in secure reliable software and productive happy teams.

More ...