Copy a Nullable property to a non Nullable version using Reflection

I am writing code to transform one object to another using reflection...

It's in progress but I think it would boil down to the following where we trust both properties have the 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 I have the additional issue that the source type might be Nullable and the target type not. e.g Nullable<int> => int. In this case I need to make sure it still works and some sensible behaviour is performed e.g. NOP or set the default value for that type.

What might this look like?

Jon Skeet
people
quotationmark

Given that GetValue returns a boxed representation, which will be a null reference for a null value of the nullable type, it's easy to detect and then handle however you 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 to copy a null value into a non-nullable type.
        // Do whatever you want here
    }
    else
    {
        targetProperty.SetValue(target, value);
    }
}

people

See more on this question at Stackoverflow