Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deep copy between objects of different types in C#.NET

I have a requirement to map all of the field values and child collections between ObjectV1 and ObjectV2 by field name. ObjectV2 is in a different namspace to ObjectV1.

Inheritence between the template ClassV1 and ClassV2 has been discounted as these 2 classes need to evolve independently. I have considered using both reflection (which is slow) and binary serialisation (which is also slow) to perform the mapping of the common properties.

Is there a preferred approach? Are there any other alternatives?

like image 896
Jon Simpson Avatar asked Feb 20 '09 11:02

Jon Simpson


People also ask

Does clone () make a deep copy?

clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable . And when you implement Cloneable , you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.

How do I copy an object from one object to another in C#?

In general, when we try to copy one object to another object, both the objects will share the same memory address. Normally, we use assignment operator, = , to copy the reference, not the object except when there is value type field. This operator will always copy the reference, not the actual object.

Does list () make a deep copy?

You don't make a deep copy using list() .


1 Answers

As an alternative to using reflection every time, you could create a helper class which dynamically creates copy methods using Reflection.Emit - this would mean you only get the performance hit on startup. This may give you the combination of flexibility and performance that you need.

As Reflection.Emit is quite clunky, I would suggest checking out this Reflector addin, which is brilliant for building this sort of code.

like image 188
Chris Ballard Avatar answered Nov 04 '22 08:11

Chris Ballard