ICloneable Interface
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
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
- Avoid using ICloneable ;)
- Read Should we Obsolete ICloneable, founding member of the CLR stating in 2004 to avoid it.
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
You May Also Like
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



