private static object ConvertValueIfNecessary(object value, Type targetType)
{
if (value != null && !targetType.IsAssignableFrom(value.GetType()))
{
// if the type is nullable, we only need to convert to the
// correct underlying type
targetType = Nullable.GetUnderlyingType(targetType) ?? targetType;
value = Convert.ChangeType(value, targetType);
}
return value;
}