3.15. 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, but the ICloneable interface should not be used, as it violates the .NET Framework Design Guidelines.
Solution
To resolve the issue with using ICloneable, create two other interfaces to establish a copying pattern, IShallowCopy<T> and IDeepCopy<T>:
public interface IShallowCopy<T>
{
T ShallowCopy();
}
public interface IDeepCopy<T>
{
T DeepCopy();
}Shallow copying means that the copied object's fields will reference the same objects as the original object. To allow shallow copying, implement the IShallowCopy<T> interface in the class:
using System;
using System.Collections;
using System.Collections.Generic;
public class ShallowClone : IShallowCopy<ShallowClone>
{
public int Data = 1;
public List<string> ListData = new List<string>();
public object ObjData = new object();
public ShallowClone ShallowCopy()
{
return (ShallowClone)this.MemberwiseClone();
}
}Deep copying or cloning means that the copied object's fields will reference new copies of the original object's fields. To allow deep copying, implement the IDeepCopy<T> interface in the class:
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; using System.IO; [Serializable] public class DeepClone : IDeepCopy<DeepClone> { public int data = 1; public List<string> ListData ...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