How do you do a deep copy of an object in .NET?

user18931 picture user18931 · Sep 24, 2008 · Viewed 479k times · Source

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

Answer

Kilhoffer picture Kilhoffer · Sep 24, 2008

I've seen a few different approaches to this, but I use a generic utility method as such:

public static T DeepClone<T>(this T obj)
{
 using (var ms = new MemoryStream())
 {
   var formatter = new BinaryFormatter();
   formatter.Serialize(ms, obj);
   ms.Position = 0;

   return (T) formatter.Deserialize(ms);
 }
}

Notes:

  • Your class MUST be marked as [Serializable] for this to work.
  • Your source file must include the following code:

    using System.Runtime.Serialization.Formatters.Binary;
    using System.IO;