I need to set the properties of a class using reflection.
I have a Dictionary<string,string> with property names and string values.
Inside a reflection loop, I need to convert the string value to the appropriate property type while setting the value for each property. Some of these property types are nullable types.
edit: The first method defined in the comments on this blog seems to do the trick as well: http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx
You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
In C# and Visual Basic, you mark a value type as nullable by using the ? notation after the value type. For example, int? in C# or Integer? in Visual Basic declares an integer value type that can be assigned null . The Nullable class provides complementary support for the Nullable<T> structure.
The Nullable type allows you to assign a null value to a variable. Nullable types introduced in C#2.0 can only work with Value Type, not with Reference Type. The nullable types for Reference Type is introduced later in C# 8.0 in 2019 so that we can explicitly define if a reference type can or can not hold a null value.
The default value of a nullable or other reference type is null while the default value for a long or other value type is 0 (and any other members set to their defaults).
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With