Per @Iridium's comment, I wound up changing to a Try pattern and return a bool as a success flag instead of throwing an InvalidCastException. Looks a lot like this:
if (!property.CanAssignValue(valueToSet))
{
Debug.Write(string.Format("The given value {0} could not be assigned to property {1}.", value, property.Name));
return false;
}
property.SetValue(instance, valueToSet, null);
return true;
The "CanAssignValue" became three quick extensions:
public static bool CanAssignValue(this PropertyInfo p, object value)
{
return value == null ? p.IsNullable() : p.PropertyType.IsInstanceOfType(value);
}
public static bool IsNullable(this PropertyInfo p)
{
return p.PropertyType.IsNullable();
}
public static bool IsNullable(this Type t)
{
return !t.IsValueType || Nullable.GetUnderlyingType(t) != null;
}
Thanks!