Jul 242011
 

It all started with list of key value pairs from file. Each key was some property on object that needed to be set and value was obviously value for that property. Since there was no type information in file, I had to use reflection in order to set value. And then problem hit me. Reflection would not sort out my problem with converting string value to proper type.

To solve it, I just loop through all key/value pairs and find property with that name in my object’s instance. Once property is found, I get a magic thing called TypeConverter. TypeConverter enables conversion from string to proper type that can be used in standard reflection SetValue call. And thus problem is solved. Code follows:

foreach (var item in pairs) {                                                                         //go through all key/value pairs
    var propertyInfo = instance.GetType().GetProperty(item.Key);                                      //find property with same name
    Trace.Assert(propertyInfo != null);                                                               //we must have this property
    var propertyConverter = TypeDescriptor.GetConverter(propertyInfo.PropertyType);                   //lets find proper converter.
    Trace.Assert(propertyConverter != null);                                                          //we must have converter
    propertyInfo.SetValue(instance, propertyConverter.ConvertFromInvariantString(item.Value), null);  //set value
}

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>