Set property Nullable<> by reflection

C&#233;dric Boivin picture Cédric Boivin · Sep 28, 2009 · Viewed 15.3k times · Source

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

Answer

Ben M picture Ben M · Sep 28, 2009

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.