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
using (var sr = new StreamReader(settingsFileName))
while ((line = sr.ReadLine()) != null)
String configValueStrs = line.Trim().Split(seps);
PropertyInfo pi = configurableProperties.Single(p => p.Name == configValueStrs.Trim());
pi.SetValue(this, pi.PropertyType.Parse(configValueStrs.Trim()), null); <-- How do I manage this?
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, pi.PropertyType) , null);