I need to deep copy an object from a class that I made to another object from the same class, I dont want to shallow copy and I dont want to use the serialization method is there any other easy methods to use??
            Asked
            
        
        
            Active
            
        
            Viewed 3,232 times
        
    -1
            
            
        - 
                    Thanks all for the answers =) – Mona Yehia May 27 '11 at 11:50
2 Answers
1
            
            
        One cheap way is to serialize it then deserialize it straight back using binary serialization.
MyObject myobj = new MyObject(); 
// ...
MemoryStream ms = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, myObj);
MemoryStream ms2 = new MemoryStream(ms.ToArray());
var myobj2 = (MyObject)formatter.Deserialize(ms2);
 
    
    
        Michael Kennedy
        
- 3,202
- 2
- 25
- 34
- 
                    1I hear you. But if you have a truly complex object graph, this might be the safest way to pull it off. Custom "deep copy" code can easily miss fields as you add them. – Michael Kennedy May 26 '11 at 00:13
- 
                    Does the creation of the second stream duplicate all of the data that has been written to the stream? – alternative May 26 '11 at 00:50
- 
                    @mathepic Yes it does. I didn't realize until after my first response that the first "answer" redirects to a similar solution: http://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically They reuse the stream by seeking it to the beginning. However, with release GC and the internals of the MemoryStream it probably reuses the array anyway. – Michael Kennedy May 26 '11 at 15:47
 
    