'casting' with reflection

jeroenh picture jeroenh · Sep 9, 2009 · Viewed 50k times · Source

Consider the following sample code:

class SampleClass
{
    public long SomeProperty { get; set; }
}

public void SetValue(SampleClass instance, decimal value)
{
    // value is of type decimal, but is in reality a natural number => cast
    instance.SomeProperty = (long)value;
}

Now I need to do something similar through reflection:

void SetValue(PropertyInfo info, object instance, object value)
{
    // throws System.ArgumentException: Decimal can not be converted to Int64
    info.SetValue(instance, value)  
}

Note that I cannot assume that the PropertyInfo always represents a long, neither that value is always a decimal. However, I know that value can be casted to the correct type for that property.

How can I convert the 'value' parameter to the type represented by PropertyInfo instance through reflection ?

Answer

Thomas Levesque picture Thomas Levesque · Sep 9, 2009
void SetValue(PropertyInfo info, object instance, object value)
{
    info.SetValue(instance, Convert.ChangeType(value, info.PropertyType));
}