I have an object model MyObject with various properties. At one point, I have two instances of these MyObject: instance A and instance B. I’d like to copy and replace the properties in instance A with those of instance B if instance B has non-null values.
If I only had 1 class with 3 properties, no problem, I could easily hard code it (which is what I started doing). But I actually have 12 different object models with about 10 properties each.
What’s good way to do this?
Update
Use AutoMapper instead if you need to invoke this method a lot. Automapper builds dynamic methods using
Reflection.Emitand will be much faster than reflection.’You could copy the values of the properties using reflection:
I’ve made it generic to ensure type safety. If you want to include private properties you should use an override of Type.GetProperties(), specifying binding flags.