views:

2596

answers:

5

Been using a Copy method with this code in it in various places in previous projects (to deal with objects that have same named properties but do not derive from a common base class or implement a common interface).

New place of work, new codebase - now it's failing at the SetValue with "Object does not match target type" even on very simple examples... and it worked last week....

    public static void Copy(object fromObj, object toObj)
    {   
        Type fromObjectType = fromObj.GetType();
        Type toObjectType = toObj.GetType();

        foreach (System.Reflection.PropertyInfo fromProperty in 
            fromObjectType.GetProperties())
        {
            if (fromProperty.CanRead)
            {
                string propertyName = fromProperty.Name;
                Type propertyType = fromProperty.PropertyType;

                System.Reflection.PropertyInfo toProperty = 
                    toObjectType.GetProperty(propertyName);

                Type toPropertyType = toProperty.PropertyType;

                if (toProperty != null && toProperty.CanWrite)
                {
                    object fromValue = fromProperty.GetValue(fromObj,null);
                    toProperty.SetValue(toProperty,fromValue,null);
                }
            }
        }
    }

    private class test
    {
        private int val;
        private string desc;

        public int Val { get { return val; } set { val = value; } }

        public string Desc { get { return desc; } set { desc = value; } }

    }

    private void TestIt()
    {
        test testo = new test();
        testo.Val = 2;
        testo.Desc = "TWO";

        test g = new test();

        Copy(testo,g);

    }

Hopefully someone can point out where I am being daft???

+2  A: 

Try:

toProperty.SetValue(toObj,fromValue,null);

You are trying to pass in the property (toProperty) as the target object, instead of toObj. For info, if you are doing lots of this, maybe consider HyperDescriptor, which can vastly reduce the reflection cost.

Marc Gravell
D'oh! that's the bug I fixed the LAST time I wrote it - and forgot to check this time...
kpollock
+1  A: 

Take a look at AutoMapper

Anton Gogolev
A: 

Should be

toProperty.SetValue(toObj,fromValue,null);
Peter Lillevold
Too slow I guess..
Peter Lillevold
A: 

Try this: http://sandrino.be/2009/03/copy-all-the-properties-of-an-object-in-c/

looks the same as mine with more compact syntax (though the if check is redundant). I prefer to be able to stick breakpoints in/examine return values from functions, hence the wordiness of mine...
kpollock
A: 

this is good but this thing fails whenever you use the vanilla classes.

Rakesh