CHAPTER 8 WORKING WITH INTERFACES
// The Point
public class
{
public int
public int
now supports "clone-ability."
Point : ICloneable
X { get; set; }
Y { get; set; }
public Point(int xPos, int yPos) { X = xPos; Y = yPos; }
public Point() { }
// Override Object.ToString().
public override string ToString()
{ return string.Format("X = {0}; Y = {1}", X, Y); }
// Return a copy of the current object.
public object Clone()
{ return new Point(this.X, this.Y); }
}
In this way, you can create exact stand-alone copies of the Point type, as illustrated by the following code:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Object Cloning *****\n");
// Notice Clone() returns a plain object type.
// You must perform an explicit cast to obtain the derived type.
Point p3 = new Point(100, 100);
Point p4 = (Point)p3.Clone();
// Change p4.X (which will not change p3.X).
p4.X = 0;
}
// Print each object.
Console.WriteLine(p3);
Console.WriteLine(p4);
Console.ReadLine();
While the current implementation of Point fits the bill, you can streamline things just a bit. Because
the Point type does not contain any internal reference type variables, you could simplify the
implementation of the Clone() method as follows:
public object Clone()
{
// Copy each field of the Point member by member.
return this.MemberwiseClone();
}
Be aware, however, that if the Point did contain any reference ty R