Reader Level:
Articles

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

By Surajit Datta on 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.
  • 0
  • 0
  • 142044

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;

    }

}

 

 

Surajit Datta

MCP, MCAD, and working as Software Engineer in Bentley Systems

COMMENT USING

Trending up