Q: How do you do a deep copy an object in .Net (C# specifically)? [duplicate]

D: I want a true deep copy. In Java, this was easy, but how do you do it in C#?

Test Case #5


File ID: #129395-0-cc


public static T DeepClone
    
     (this T a)
{
    using (MemoryStream stream = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, a);
        stream.Position = 0;
        return (T) formatter.Deserialize(stream);
    }
}

    

  1. This only works if all members are marked [Serializable]
  2. Recursive MemberwiseClone will do deep copy too, it works 3 times faster then BinaryFormatter, doesn't require default constructor or any attributes. See my answer: http://stackoverflow.com/a/11308879/235715
  3. Event subscribes are included into serialization graph, since BinaryFormatter uses fields via reflection, and events are just fields of delegate types plus add/remove/invoke methods. You can use [field: NonSerialized] on event to avoid this.

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: