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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access