I try to set a Nullable<> property dynamicly.
I Get my property ex :
PropertyInfo property = class.GetProperty(\"PropertyName\"); // My property i
If you want to convert an arbitrary string to the underlying type of the Nullable, you can use the Convert class:
var propertyInfo = typeof(Foo).GetProperty("Bar");
object convertedValue = null;
try
{
convertedValue = System.Convert.ChangeType("1256",
Nullable.GetUnderlyingType(propertyInfo.PropertyType));
}
catch (InvalidCastException)
{
// the input string could not be converted to the target type - abort
return;
}
propertyInfo.SetValue(fooInstance, convertedValue, null);
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.