I try to set a Nullable<> property dynamicly.
I Get my property ex :
PropertyInfo property = class.GetProperty(\"PropertyName\"); // My property i
I hit this same problem as well as an issue with Convert.ChangeType not handling DateTimes on Nullables so I combined a couple of stackoverflow solutions with some .NET 4 dynamic magic to get something I think is kind of sweet. If you look at the code, we use dynamic to type the object to Nullable at run time, then the run time treats it differently and allows assignments of the base type to the nullable object.
public void GenericMapField(object targetObj, string fieldName, object fieldValue)
{
PropertyInfo prop = targetObj.GetType().GetProperty(fieldName);
if (prop != null)
{
if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
dynamic objValue = System.Activator.CreateInstance(prop.PropertyType);
objValue = fieldValue;
prop.SetValue(targetObj, (object)objValue, null);
}
else
{
prop.SetValue(targetObj, fieldValue, null);
}
}
}