3.28. Building Cloneable Classes

Problem

You need a method of performing a shallow cloning operation, a deep cloning operation, or both on a data type that may also reference other types.

Solution

Shallow copying means that the copied object’s fields will reference the same objects as the original object. To allow shallow copying, add the following Clone method to your class:

using System;
using System.Collections;

public class ShallowClone : ICloneable
{
    public int data = 1;
    public ArrayList listData = new ArrayList( );
    public object objData = new object( );

    public object Clone( )
    {
        return (this.MemberwiseClone( ));
    }
}

Deep copying or cloning means that the copied object’s fields will reference new copies of the original object’s fields. This method of copying is more time-consuming than the shallow copy. To allow deep copying, add the following Clone method to your class:

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

[Serializable]
public class DeepClone : ICloneable
{
    public int data = 1;
    public ArrayList listData = new ArrayList( );
    public object objData = new object( );

    public object Clone( )
    {
        BinaryFormatter BF = new BinaryFormatter( );
        MemoryStream memStream = new MemoryStream( );

        BF.Serialize(memStream, this);
        memStream.Flush( );
        memStream.Position = 0;

        return (BF.Deserialize(memStream));
    }
}

Add an overloaded Clone method to your class to allow for deep or shallow copying. This method allows you to decide ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.