O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required