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.
I wrote this as an extension method that works with different types too. My issue was that I have some models bound to asp mvc forms, and other entities mapped to the database. Ideally I would only have 1 class, but the entity is built in stages and asp mvc models want to validate the entire model at once.
Here is the code:
Hmm. I thought
GetFields
gets you members from all the way up the chain, and you had to explicitly specifiyBindingFlags.DeclaredOnly
if you didn't want inherited members. So I did a quick test, and I was right.Then I noticed something:
This will get only fields (including private fields on this type), but not properties. So if you have this hierarchy (please excuse the names!):
then a
.GetFields
onL2
with theBindingFlags
you specify will getf0
,f1
,f2
, and_p2
, but NOTp0
orp1
(which are properties, not fields) OR_p0
or_p1
(which are private to the base classes and hence an objects of typeL2
does not have those fields.If you want to copy properties, try doing what you're doing, but using
.GetProperties
instead.This doesn't take into account properties with parameters, nor does it consider Private get/set accessors which may not be accessible, nor does it consider read-only enumerables, so here's an extended solution?
I tried converting to C#, but the usual sources for that failed to do so and I don't have the time to convert it myself.
Try this:
Bogdan Litescu's solution works great, although I would also check if you can write to property.