Technology with opinion

Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Wednesday, April 07, 2010

Automatically mapping objects of same derived types

I had a need to automatically map all properties from one class to another class. These two classes had the same derived type, this was by design and not by accident. FYI: this example's Unit Test uses NUnit (2.5), NBuilder, both are optional as the test below can be easily adapted.

The scenario goes like this: you have a base class called BaseTransaction with derived classes DebitTransaction and CreditTransaction. Often where there are many properties from the base class to map, it's redundant to write and tedious. This bit of reflection below iterates through each property of the base class and maps it to a new object that it creates and returns this object.

The following unit test shows the usage of this function, as well as outputs to the console showing that the bases members were in fact mapped. Each derived class has unique properties of the same name (TransactionId), neither of these were mapped - otherwise an exception would have been thrown during the reflection code (prop.SetValue...).