Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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???
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.