CHAPTER 8 WORKING WITH INTERFACES
A More Elaborate Cloning Example
Now assume the Point class contains a reference type member variable of type PointDescription. This
class maintains a point’s friendly name as well as an identification number expressed as a System.Guid (a
globally unique identifier [GUID] is a statistically unique 128-bit number). Here is the implementation:
// This class describes a point.
public class PointDescription
{
public string PetName {get; set;}
public Guid PointID {get; set;}
}
public PointDescription()
{
PetName = "No-name";
PointID = Guid.NewGuid();
}
The initial updates to the Point class itself included modifying ToString() to account for these new
bits of state data, as well as defining and creating the PointDescription reference type. To allow the
outside world to establish a pet name for the Point, you also update the arguments passed into the
overloaded constructor:
public class Point : ICloneable
{
public int X { get; set; }
public int Y { get; set; }
public PointDescription desc = new PointDescription();
public Point(int xPos, int yPos, string petName)
{
X = xPos; Y = yPos;
desc.PetName = petName;
}
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}; Name = {2};\nID = {3}\n",
X, Y, desc.PetName, desc.PointID);
}
}
310
// Return a copy of the current object.
public object Clone()
{ return this.MemberwiseClone(); }