Cloning

We know that when we assign one reference-type object to another, both the objects point to the same memory location after the operation is completed. If a member field in one object is changed, for example, it gets reflected in the other object.

Sometimes you might want to clone the object, i.e., create a duplicate copy of the object. The .NET Framework formalizes this notion of cloning by meaning of a standard interface, ICloneable. Here is its definition:

public interface ICloneable {
     Object Clone();
}

The interface defines just one method, Clone. The purpose of this method is to return a clone of the object. Any class that implements ICloneable must implement Clone and the necessary logic to duplicate the object.

Interface ICloneable is implemented by many classes in the BCL. All the collection classes that we covered earlier implement this interface.

The simplest implementation of Clone could just invoke System .Object.MemberwiseClone, as illustrated in the following code excerpt:

// Project Cloning

class Student : ICloneable {
     public String Name;
     public int Grade;

     public Object Clone() {
       return this.MemberwiseClone();
     }
}

class MyApp {
     public static void Main() {

       // Create s1
       Student s1 = new Student();
       ...

       // Clone s1 to s2
       Student s2 = (Student) s1.Clone();
       ...
     }
}

The MemberwiseClone method makes a shallow copy of the object; that is, if the object contains a reference-type field, the cloned object points to the same reference. Only the value-type fields are truly duplicated.

If this shallow copy behavior is not desired, it is up to you to provide your own deep-copy semantics when you implement Clone.

A related note on the collection classes: Most of them implement ICloneable as a shallow copy. If you require deep-copy semantics on, for example, an ArrayList, derive your own class from ArrayList and override the method Clone.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.129.100