ARTICLE

Deep Copy in C# (Cloning for a user defined class)

Posted by Surajit Datta Articles | Visual C# May 04, 2007
For deep copy of a user defined class, a class should implement ICloneable interface. The attached code in this article shows how to build clonable classes.
Reader Level:

Have you ever used the Clone() method of DataSet? This method creates an empty class with same structure as original DataSet.

 

You can write your own clonable classes. To do so, you must implement IClonable. The following code shows a clonable Test class.

 

using System.IO;

using System.Runtime.Serialization.Formatters.Binary;


public Class Test : IClonable

{

    public Test()

    {

    }

    // deep copy in separeate memory space

    public object Clone()

    {

        MemoryStream ms = new MemoryStream();

        BinaryFormatter bf = new BinaryFormatter();

        bf.Serialize(ms, this);

        ms.Position = 0;

        object obj = bf.Deserialize(ms);

        ms.Close();

        return obj;

    }

}

 

 

Login to add your contents and source code to this article
post comment
     

That was a nice one Surajit. Thanks a lot. But for the use in the Silverlight the following stub works as IClonable is not available.

public static T DeepCopy(this T objectToCopy)
{
T copy;
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream()) {
serializer.WriteObject(ms, objectToCopy);
ms.Position = 0;
copy = (T)serializer.ReadObject(ms);
}
return copy;
}

Posted by Shyam Mar 19, 2010

Cool! thx!

Posted by Alejandro Jun 18, 2009

This only works with classes that are serializable (they have the SerializeableAttribute or implement ISerializeable). Plus, ICloneable is deprecated. See Framework Design Guidelines (http://blogs.msdn.com/brada/archive/2003/04/09/49935.aspx) and Item 27 of Effective C#

Posted by Peter Ritchie Feb 11, 2008

Is there a straightforward way to clone a non-serializable class? how can i clone a Datagrid, which is non-serializable, without using reflections?

Posted by Thinathayalan Ganesan May 04, 2007
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.