c# - Copy a Nullable property to a non-Nullable version using Reflection -


i writing code transform 1 object using reflection...

it's in progress think boil down following trust both properties have same type:

    private void copypropertyvalue(object source, string sourcepropertyname, object target, string targetpropertyname)     {         propertyinfo sourceproperty = source.gettype().getproperty(sourcepropertyname);         propertyinfo targetproperty = target.gettype().getproperty(targetpropertyname);         targetproperty.setvalue(target, sourceproperty.getvalue(source));     } 

however have additional issue source type might nullable , target type not. e.g nullable<int> => int. in case need make sure still works , sensible behaviour performed e.g. nop or set default value type.

what might like?

given getvalue returns boxed representation, null reference null value of nullable type, it's easy detect , handle want:

private void copypropertyvalue(     object source,     string sourcepropertyname,     object target,     string targetpropertyname) {     propertyinfo sourceproperty = source.gettype().getproperty(sourcepropertyname);     propertyinfo targetproperty = target.gettype().getproperty(targetpropertyname);     object value = sourceproperty.getvalue(source);     if (value == null &&          targetproperty.propertytype.isvaluetype &&         nullable.getunderlyingtype(targetproperty.propertytype) == null)     {         // okay, trying copy null value non-nullable type.         // whatever want here     }     else     {         targetproperty.setvalue(target, value);     } } 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -