ICloneable Interface

Overview

  • Enable objects to be cloned.
  • Does not specify if you need to implement deep-copy or shallow-copy. (Problematic in public APIs)

Good practice

Examples

Object Cloning

class MyNumber: ICloneable
{
    private int _x;
 
    public int X
    {
        get { return this._x; }
        set { this._x = value; }
    }
 
    public MyNumber(int x)
    {
        this._x = x;
    }
 
    #region ICloneable Members
    public object Clone()
    {
        return new MyNumber(this.X);
    }
    #endregion
}
MyNumber a = new MyNumber(10);
MyNumber b = (MyNumber)a.Clone();
MyNumber c = a;
a.X += 100; // Incremented to display b.X does not get incremented, while c.X does.
Console.WriteLine(a.X); // Prints 110
Console.WriteLine(b.X); // Prints 10
Console.WriteLine(c.X); // Prints 110
 
learning/exam70-536/icloneable.txt · Last modified: 2008/08/26 12:27 by david
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki