C# Parse string to type known at runtime

21,434

Solution 1

You can use the static Convert.ChangeType method for that. It takes an object as its first parameter and a Type instance you want to convert the object to. The return value is of the type you requested or null if no suitable conversion was found. This method throw 4 different exceptions, from which three are caused by the value it tries to convert. You might want to catch and handle these.

Use the function as follows in your example:

// Convert.ChangeType can throw if the string doesn't convert to any known type
    pi.SetValue(this
      , Convert.ChangeType(configValueStrs[1], pi.PropertyType) 
      , null); 

Solution 2

TypeConverters are the way to go. Take a look here for a good example of what to do.

Nicked straight from hanselmans blog:

public static T GetTfromString<T>(string mystring)
{
   var foo = TypeDescriptor.GetConverter(typeof(T));
   return (T)(foo.ConvertFromInvariantString(mystring));
}

Solution 3

I believe that TypeConverters, Specifically StringConverter can help you with this problem.

http://msdn.microsoft.com/en-us/library/system.componentmodel.stringconverter.aspx

Share:
21,434
bavaza
Author by

bavaza

Updated on July 09, 2022

Comments

  • bavaza
    bavaza almost 2 years

    I have a file holding some of the variables of a class, and each line is a pair : variable, value. I'm looking for a way to load these at runtime (a-la XmlSerializer), using reflection.

    Is there a way to parse a string into a Type known only at runtime?

    The following is a wishful code sample where the last line (with the pi.SetValue() is not correct, because PropertyType is of class Type which does not have a generic Parse() method.

    using (var sr = new StreamReader(settingsFileName))
    {
        String  line;
        while ((line = sr.ReadLine()) != null)
        {
            String[] configValueStrs = line.Trim().Split(seps);
    
            PropertyInfo pi = configurableProperties
                    .Single(p => p.Name == configValueStrs[0].Trim());
    
            //How do I manage this?
            pi.SetValue(this, pi.PropertyType.Parse(configValueStrs[1].Trim()), null);
         }
     }
    

    Since all of the relevant variables are Ints, Doubles, Strings or Booleans, as a last resort, I can Switch on the type and use the corresponding ToType() method, but I bet there is a more elegant solution.

  • Arical
    Arical over 12 years
    +1 to this as it will handle GUIDS, Convert.ChangeType will not
  • Peter
    Peter about 12 years
    Check this: chrismarinos.com/default-typeconverters-and-objects Also in my own experience, the default implementation can't do anything.
  • Peter
    Peter about 12 years
    Thanks, helped me out of a sticky situation!
  • cdiggins
    cdiggins over 2 years
    Good answer, but that code is rather inelegant, and in some cases you have the type at run-time, not compile-time. See: stackoverflow.com/a/70354581/184528