I try to set a Nullable<> property dynamicly.
I Get my property ex :
PropertyInfo property = class.GetProperty("PropertyName"); // My property is Nullable<> at this time So the type could be a string or int
I want to set my property by reflection like
property.SetValue(class,"1256",null);
It's not working when my property is a Nullable<> Generic. So i try to find a way to set my property.
To know the type of my nullable<> property i execute
Nullable.GetUnderlyingType(property.PropertyType)
Any idea ?
I Try to create an instance of my Nullable<> property with
var nullVar = Activator.CreateInstance(typeof(Nullable<>).MakeGenericType(new Type[] { Nullable.GetUnderlyingType(property.PropertyType) }));
But nullVar is always Null
If you want to convert an arbitrary string to the underlying type of the Nullable, you can use the Convert class:
This example will work if the target type is int, short, long (or unsigned variants, since the input string represents a non-negative number), double, float, or decimal. Caveat: this is not fast code.
I hit this same problem as well as an issue with Convert.ChangeType not handling DateTimes on Nullables so I combined a couple of stackoverflow solutions with some .NET 4 dynamic magic to get something I think is kind of sweet. If you look at the code, we use dynamic to type the object to Nullable at run time, then the run time treats it differently and allows assignments of the base type to the nullable object.
If it's a nullable int, you'll need to use an int parameter, not a string.
Note the change to klass, instead of class, as class is a reserved keyword. You could also use @class if absolutely necessary (quoting it).
If your property is a generic, then I think you'll probably need to use Convert to convert whatever you have to whatever you need.
Here is a complete example showing how to do it:
As others have mentioned you need to pass the right type to the
SetValue
function but your other reflection code is not quite right either. You need to get the type of the class in question before you can query for its members.Edit: If I understand correctly you are trying to set a string value to any property via reflection. In order to do this you will need to do some type inspection and type conversion.
Here is an example of what I mean:
This approach can be safely used regardless of whether or not the property is
Nullable<>
."1256"
is a string, not an int.