Anyone have a suggestion for a good utility class that maps values from one object to another? I want a utility class that uses reflection and takes two objects and copies values from the 1st object to the second if there is a public property with the same name.
I have two entities that are generated from a web service proxy, so I can’t change the parent class or impliment an interface or anything like that. But I know that the two objects have the same public properties.
Jon Skeet and Marc Gravell have a library called MiscUtil. Inside
MiscUtil.Reflectionthere is a class calledPropertyCopythat does exactly what you describe. It only works for .NET 3.5.It works by running over the public properties of the SourceType, matches them up by name with the public properties of the TargetType, makes sure that each property can be assigned from the source to the target and then creates and caches a copier function for those two types (so you don’t do all this reflection every time). I’ve used it in production code and can vouch for its goodness.
What the hey, I figured I’d just post their concise code (it’s less than 100 lines w/comments). The license for this code can be found here: