So I have written a program in which I need to do a deep copy of several objects. In my case I cannot use serialization which would’ve solved this problem with ease. Is there another way to solve this problem without manually copying all the attributes in the classes?
Share
You could do this using reflection. Code project has an example: http://www.codeproject.com/Articles/38270/Deep-copy-of-objects-in-C
UPDATE 1
There are also examples on StackOverflow using
BinaryFormatter, as noted in the comments to your question:How do you do a deep copy of an object in .NET (C# specifically)?
Deep cloning objects
If you want another approach, then if possible you can make all of your classes implement
ICloneable, make use of MemberwiseClone, and use recursion to do the deep copy. Personally, I’d start withBinaryFormatter.UPDATE 2
If
GameComponentis not serializable (which judging from the documentation it does not appear to be), then you could use this pattern to help create copies of your classes that derive fromGameComponent. Wrap all of the data you need to copy in its own class and mark that class as serializable, and then implementICloneableon yourGameComponentclass. For example: