Is there any generic Parse() function that will convert a string to any type using parse?

Viewed 49850

I want to convert a string to a generic type like int or date or long based on the generic return type.

Basically a function like Parse<T>(String) that returns an item of type T.

For example if a int was passed the function should do int.parse internally.

5 Answers

cleaner version of Pranay's answer

public static T ConvertTo<T>(this object value)
{
    if (value is T variable) return variable;

    try
    {
        //Handling Nullable types i.e, int?, double?, bool? .. etc
        if (Nullable.GetUnderlyingType(typeof(T)) != null)
        {
            return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value);
        }

        return (T)Convert.ChangeType(value, typeof(T));
    }
    catch (Exception)
    {
        return default(T);
    }
}

System.Convert.ChangeType does not convert to any type. Think of the following:

  • nullable types
  • enums
  • Guid etc.

These conversions are possible with this implementation of ChangeType.

There are a couple of conventions in the .NET to convert objects of one type to another.

But these methods are much slower than your typical T.Parse(string), cause boxing and involve lots of allocations each time you want to convert a single value.

For ValueString, I chose to find a suitable, static parsing method of the type using reflection, build a lambda expression calling it and cache the compiled delegate for future use (See this answer for an example).

It also fallbacks to the ways I mentioned above if the type doesn't have a suitable parsing method (See the performance section in the readme).

var v = new ValueString("15"); // struct
var i = v.As<int>(); // Calls int.Parse.
Related