Hi Guys
NP91 Clone() method
Following program is producing same result even if following codes are commented out. What is the significant of the codes.
copyPtDesc.petName = this.desc.petName;
copyPtDesc.creationDate = this.desc.creationDate;
Anyone knows please explain the reason.
Thank you
using System;
namespace ObjClone
{
#region The point description type
// This class describes a point.
public class PointDesc
// Public for easy access.
public string petName;
public DateTime creationDate;
public PointDesc(string petName)
this.petName = petName;
// Inject a time lag to get different times.
System.Threading.Thread.Sleep(2000);
creationDate = DateTime.Now;
}
public string CreationTime()
// Return a string with date/time information.
return creationDate.ToString();
#endregion
#region Cloneable point type
// The Point class supports deep copy semantics ala ICloneable.
public class Point : ICloneable
// State data.
public int x, y;
public PointDesc desc;
// Ctors.
public Point() { }
public Point(int x, int y, string petname)
this.x = x;
this.y = y;
desc = new PointDesc(petname);
// The sole method of ICloneable.
public object Clone()
// return this.MemberwiseClone();
// Now we need to adjust for the PointDesc type.
Point copyPt = new Point();
copyPt.x = this.x;
copyPt.y = this.y;
PointDesc copyPtDesc = new PointDesc(this.desc.petName);
copyPt.desc = copyPtDesc;
return copyPt;
// Override Object.ToString().
public override string ToString()
return "X: " + x + " Y: " + y +
" PetName: " + desc.petName +
" Time of creation: " + desc.CreationTime();
public class CloneApp
public static int Main(string[] args)
// Two references to same object!
Console.WriteLine("***** Assigning points *****");
Point p1 = new Point(50, 50, "Fred");
Point p2 = p1;
p2.x = 0;
// Print each obj.
Console.WriteLine("p1 is {0}", p1);
Console.WriteLine("p2 is {0}\n", p2);
// Now Clone object.
Console.WriteLine("***** Cloning p3 and holding in p4 *****");
Point p3 = new Point(100, 100, "Jane");
Point p4 = (Point)p3.Clone();
Console.WriteLine("-> Before pet name modification");
Console.WriteLine("p3: {0}", p3);
Console.WriteLine("p4: {0}", p4);
p4.desc.petName = "XXXXX";
Console.WriteLine("\n-> After pet name modification");
Console.WriteLine("p4: {0}\n", p4);
return 0;
/*
***** Assigning points *****
p1 is X: 0 Y: 50 PetName: Fred Time of creation: 3/27/2008 1:34:12 PM
p2 is X: 0 Y: 50 PetName: Fred Time of creation: 3/27/2008 1:34:12 PM
***** Cloning p3 and holding in p4 *****
-> Before pet name modification
p3: X: 100 Y: 100 PetName: Jane Time of creation: 3/27/2008 1:34:14 PM
p4: X: 100 Y: 100 PetName: Jane Time of creation: 3/27/2008 1:34:14 PM
-> After pet name modification
p4: X: 100 Y: 100 PetName: XXXXX Time of creation: 3/27/2008 1:34:14 PM
*/