I save the update operation as follows:
class Update { public Expression MemberExpression { get; set; } public Type FieldType { get; set; } public object NewValue { get; set; } }
For instance:
var myUpdate = new Update { MemberExpression = (MyType o) => o.LastModified, FieldType = typeof(DateTime?), NewValue = (DateTime?)DateTime.Now }
Then I try to apply this update later (simplified):
var lambda = myUpdate.MemberExpression as LambdaExpression; var memberExpr = lambda.Body as MemberExpression; var prop = memberExpr.Member as PropertyInfo; prop.SetValue(item, myUpdate.Value);
However, myUpdate.Value is a DateTime , not a DateTime? . This is because when you assign a nullable value to an object it either becomes null or enters a value type.
Since (DateTime?)myUpdate.Value will work to return it to the correct type, I tried to simulate this compile-time construct using Convert.ChangeType . However, it says casting from DateTime to DateTime? impossible.
What approach can I use here to return an object to its original type?
Is there a way to store types with zero value, regular structures and regular objects in one field and return exact data to it?
source share