Overview
- Enables objects to be cloned.
- Does not specify if you need to implement a deep copy or a shallow copy, which is problematic in public APIs.
Good practice
- Avoid using ICloneable ;)
- Read Should we Obsolete ICloneable, in which Brad Abrams, a founding member of the CLR team, advised 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

Exam 70-536 Study Notes
My study notes for Microsoft exam 70-536: .NET types, collections, generics, I/O, serialization and more, with C# examples.

Starting Exam 70-536 Study
After a burnout, I'm putting my own project on hold to study for Microsoft exam 70-536.

Design Patterns - Proxy Pattern
The Proxy Pattern, and the last article in the design patterns series, now that I've finished reading Head First Design Patterns.




