views:

222

answers:

2

I want to use reflection to set some fields according to data from a file. The information that I can have is TypeName, TypeValue and FieldName.

While this is trivial on classes (Activator.CreateInstance and PropertyInfo.SetValue), I am a bit dumbstruck when it comes to value types like Int32 which does not have any properties. I see that IsValueType is true on those Types, but as my TypeValue is a string (i.e. string TypeValue = "400"), I don't know how to assign it.

Do I have to use GetMethods() to check if there is a .Parse Method? Is this something for a TypeConverter?

I know I could just hardcode some common value types (there aren't that many anyway) and have a big switch() statement, but I wonder if there is something that automagically does a "Convert String to T" conversion?

+6  A: 
// get the type converters we need
TypeConverter myConverter = TypeDescriptor.GetConverter(typeof(int));

// get the degrees, minutes and seconds value
int Degrees = (int)myConverter.ConvertFromString(strVal);

this should help

ArsenMkrt
It does, the TypeDescriptor class is the magic I was looking for, Thanks!
Michael Stum
+3  A: 

ArsenMkrt is right; TypeConverter is the way to go here; some extra thoughts, though:

You might consider using "component model" rather than reflection; i.e. instead of typeof(T).GetProperties(), consider TypeDescriptor.GetProperties(typeof(T)). This gives you a set of PropertyDescriptor records instead of the reflection PropertyInfo. Why is this handy?

  • because people can actually specify a converter per property (below) - this is exposed as prop.Converter on PropertyDescriptor
  • if the file is big, you can get a performance boost by using HyperDescriptor

As an example of a property with custom converter:

[TypeConverter(typeof(CurrencyConverter))] // bespoke
public decimal TotalPrice {get;set;}
Marc Gravell