Introduction
This article describes a method to automatically copy data from an object to another object with similar structures. This is similar to a deep_copy(source, destination) but with the possibility of returning a type that is different from the source.
Background
If you have worked with WCF services, you have noticed that versioning can lead to a lot of code duplication. My problem showed up when a service of version 2.0 was using almost the exact structures as in version 1.0 and I wanted to use the same service workflow code, but with different structures.
I needed a way to apply/convert values from one object to another so I created a method to automatically drill down the source object graph and copy the properties from one object to another.
There are many ways to do this, but I designed a method that is generic enough and also leaves place for customization/fine tuning/hacking.
Basically, what I needed was the ability to do this automatically:
service_version1.Customer.Name = service_version2.Customer.Name;
service_version1.Customer.Address.Street = service_version2.Customer.Address.Street;
How to use
Although there are some gotchas, the basic usage is as follows.
Include files PropertiesCopier.cs and (optionally) PropertiesCopier.Checks.cs in your project.
Call PropertiesCopier.CopyProperties on your source and destination objects.
PropertiesCopier.CopyProperties(sourceObject, destinationObject);
More...