Convert.ChangeType() fails on Nullable Types

I want to convert a string to an object property value, whose name I have as a string. I am trying to do this like so:

string modelProperty = "Some Property Name";
string value = "SomeValue";
var property = entity.GetType().GetProperty(modelProperty);
if (property != null) {
    property.SetValue(entity, 
        Convert.ChangeType(value, property.PropertyType), null);
}

The problem is this is failing and throwing an Invalid Cast Exception when the property type is a nullable type. This is not the case of the values being unable to be Converted – they will work if I do this manually (e.g. DateTime? d = Convert.ToDateTime(value);) I’ve seen some similiar questions but still can’t get it to work.

7 Answers
7

Leave a Comment