Tuesday, August 28, 2012

Deep copy of C# object properties

Sometimes you have two different class types with the same properties and you want to copy all the property values from one to the other.

One way is to simply hand code one assignment statement for each field they have in common.

Another option is to use an open source mapping library like AutoMapper

Still other times you might find yourself in the middle ground of not wanting to hand code all the assignments and also not wanting to deal with a 3rd party library.

Here is an example of how you can roll your own automapper in a few lines of code.  This snippet copies like-named properties from a source to a target.  It recurses on any properies that don't have a type starting with "System." and it ignores source properties with value of null.

No comments:

Post a Comment