views:

230

answers:

3

I'm attempting to map values of properties (via reflection) between different objects. This appears to be failing oddly on nullable value types. The following code:

 destProperty.SetValue(destObject, sourceProperty.GetValue(sourceObject, null), null);

sets destProperty to null if destProperty is a nullable value type, despite sourceProperty having a value.

Surely this is a fairly common task - I must be missing something simple?

+1  A: 

What you posted works for me. Just ran the following. destObject.b is equal to 110 afterwards. notice the final code line is verbatim what you posted.

class Foo {

    public int? a { get; set; }
    public int? b { get; set; }

    static void Main(string[] args) {

        var destObject = new Foo { a = 1, b = 2 };
        var sourceObject = new Foo { a = 110, b = 112 };
        var destProperty = typeof(Foo).GetProperty("b");
        var sourceProperty = typeof(Foo).GetProperty("a");

        destProperty.SetValue(destObject, sourceProperty.GetValue(sourceObject, null), null);
    }
}
Jimmy
Hmm - I just managed to get it to work in a simple test case also. I'll have to do more digging to see where it's going wrong.
Sam
+1  A: 

Looks good - I get the right value in Destination:

internal class Test
{
    public Test()
    {
        Source = 15;
    }

    public int? Source { get; private set; }
    public int? Destination { get; private set; }
}


var testType = typeof( Test );
var sourceProperty = testType.GetProperty( "Source" );
var destProperty = testType.GetProperty( "Destination" );
var test = new Test();
destProperty.SetValue( test, sourceProperty.GetValue( test, null ), null );
tanascius
A: 

It was something simple - destProperty on this particular class seems to be written to ignore set calls unless certain other properties are set first. I'm pretty sure I wouldn't have been responsible for such a flagrant violation of our coding standards, so I'm going to blame this one on the other guy. Pretty sure.

Thanks to Jimmy & tanascius for confirming it should work.

Sam