Free mag vol1 | Page 373

CHAPTER 8  WORKING WITH INTERFACES Notice that you did not yet update your Clone() method. Therefore, when the object user asks for a clone using the current implementation, a shallow (member-by-member) copy is achieved. To illustrate, assume you have updated Main() as follows: static void Main(string[] args) { Console.WriteLine("***** Fun with Object Cloning *****\n"); Console.WriteLine("Cloned p3 and stored new Point in p4"); Point p3 = new Point(100, 100, "Jane"); Point p4 = (Point)p3.Clone(); Console.WriteLine("Before modification:"); Console.WriteLine("p3: {0}", p3); Console.WriteLine("p4: {0}", p4); p4.desc.PetName = "My new Point"; p4.X = 9; } Console.WriteLine("\nChanged p4.desc.petName and p4.X"); Console.WriteLine("After modification:"); Console.WriteLine("p3: {0}", p3); Console.WriteLine("p4: {0}", p4); Console.ReadLine(); Notice in the following output that while the value types have indeed been changed, the internal reference types maintain the same values, as they are “pointing” to the same objects in memory (specifically, note that the pet name for both objects is now “My new Point”). ***** Fun with Object Cloning ***** Cloned p3 and stored new Point in p4 Before modification: p3: X = 100; Y = 100; Name = Jane; ID = 133d66a7-0837-4bd7-95c6-b22ab0434509 p4: X = 100; Y = 100; Name = Jane; ID = 133d66a7-0837-4bd7-95c6-b22ab0434509 Changed p4.desc.petName and p4.X After modification: p3: X = 100; Y = 100; Name = My new Point; ID = 133d66a7-0837-4bd7-95c6-b22ab0434509 p4: X = 9; Y = 100; Name = My new Point; ID = 133d66a7-0837-4bd7-95c6-b22ab0434509 To have your Clone() method make a complete deep copy of the internal reference types, you need to configure the object returned by MemberwiseClone() to account for the current point’s name (the 311