I need to set the properties of a class using reflection.
I have a Dictionary
with property names and string values.
Inside
One way to do this is:
type.GetGenericTypeDefinition() == typeof(Nullable<>)
Just set is as per any other reflection code:
propertyInfo.SetValue(yourObject, yourValue);
Why do you need to know if it is nullable? And do you mean "reference-type", or "Nullable<T>
"?
Either way, with string values, the easiest option would be via the TypeConverter
, which is more-easily (and more accurately) available on PropertyDescriptor
:
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj);
// then per property...
PropertyDescriptor prop = props[propName];
prop.SetValue(obj, prop.Converter.ConvertFromInvariantString(value));
This should use the correct converter, even if set per-property (rather than per-type). Finally, if you are doing lots of this, this allows for acceleration via HyperDescriptor, without changing the code (other than to enable it for the type, done once only).