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

48,246

Solution 1

System.Convert.ChangeType

As per your example, you could do:

int i = (int)Convert.ChangeType("123", typeof(int));
DateTime dt = (DateTime)Convert.ChangeType("2009/12/12", typeof(DateTime));

To satisfy your "generic return type" requirement, you could write your own extension method:

public static T ChangeType<T>(this object obj)
{
    return (T)Convert.ChangeType(obj, typeof(T));
}

This will allow you to do:

int i = "123".ChangeType<int>();

Solution 2

Well looks like I am too late for answering on this thread. But here is my implementation:

Basically, I have created an Extention method for the Object class. It handles all the types, i.e nullable, classes, and struct.

 public static T ConvertTo<T>(this object value)
           {
               T returnValue;

               if (value is T variable)
                   returnValue = variable;
               else
                   try
                   {
                       //Handling Nullable types i.e, int?, double?, bool? .. etc
                       if (Nullable.GetUnderlyingType(typeof(T)) != null)
                       {
                           TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
                           returnValue = (T) conv.ConvertFrom(value);
                       }
                       else
                       {
                           returnValue = (T) Convert.ChangeType(value, typeof(T));
                       }
                   }
                   catch (Exception)
                   {
                       returnValue = default(T);
                   }

               return returnValue;
           }

Solution 3

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);
    }
}

Solution 4

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.

Share:
48,246

Related videos on Youtube

Karim
Author by

Karim

Updated on August 26, 2020

Comments

  • Karim
    Karim over 3 years

    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.

  • Karim
    Karim over 13 years
    cool , but the strange thing its named ChangeType , so i would thought that this function does some kind of cast and not parse
  • Ani
    Ani over 13 years
    MSDN says it is simply a wrapper that finds the right conversion method on the source object, requiring that it implements the IConvertible interface.
  • Liam
    Liam over 8 years
    If it needs to implement IConvertable shouldn't you also constrain the T, i.e. T ChangeType<T>(this object obj) where T : IConvertable?
  • Ani
    Ani over 8 years
    @Liam: No, it's obj that must be IConvertible, but there's no way to specify that at compile-time.
  • Hopeless
    Hopeless over 8 years
    if I need something like TryChangeType that returns null or false in fail case? Only by catching exception?
  • Ole Albers
    Ole Albers about 6 years
    IMHO this is the better answer cause it also contains the "nullable"-aspect
  • Luke T O'Brien
    Luke T O'Brien about 5 years
    I am doing exactly this in my code.... The trouble is is won't cast 1 as a boolean. Is there a generic way of handling all value types
  • IMujagic
    IMujagic over 4 years
    is there a specific reason why you are using TypeDescriptor for nullable types and Convert.ChangeType for non-nullable ones? This whole try block can be reduced only to TypeConverter 2 lines of code and it will work for both, nullable and non-nullable.