
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Building Cloneable Classes
|
183
3.26 Building Cloneable Classes
Problem
You need a method of performing a shallow cloning operation, a deep cloning opera-
tion, 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;
using System.Collections.Generic;
public class ShallowClone : ICloneable
{
public int data = 1;
public List<string> listData = new List<string>( );
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 cop-
ies 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.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
[Serializable]
public class DeepClone : ICloneable
{
public int data = 1;
public List<string> listData = new List<string>( );
public object objData = new object( );
public object Clone( )
{
BinaryFormatter BF ...