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 ...
Get C# 3.0 Cookbook, 3rd Edition 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.