C# Using Reflection to copy base class properties

Posted by David Liddle on Stack Overflow See other posts from Stack Overflow or by David Liddle
Published on 2009-07-29T08:57:28Z Indexed on 2010/03/17 4:51 UTC
Read the original article Hit count: 963

Filed under:
|
|

I would like to update all properties from MyObject to another using Reflection. The problem I am coming into is that the particular object is inherited from a base class and those base class property values are not updated.

The below code copies over top level property values.

public void Update(MyObject o)
{
    MyObject copyObject = ...

    FieldInfo[] myObjectFields = o.GetType().GetFields(
    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

    foreach (FieldInfo fi in myObjectFields)
    {
        fi.SetValue(copyObject, fi.GetValue(o));
    }
}

I was looking to see if there were any more BindingFlags attributes I could use to help but to no avail.

© Stack Overflow or respective owner

Related posts about c#

Related posts about reflection