Free mag vol1 | Page 374

CHAPTER 8  WORKING WITH INTERFACES System.Guid type is in fact a structure, so the numerical data is indeed copied). Here is one possible implementation: // Now we need to adjust for the PointDescription member. public object Clone() { // First get a shallow copy. Point newPoint = (Point)this.MemberwiseClone(); } // Then fill in the gaps. PointDescription currentDesc = new PointDescription(); currentDesc.PetName = this.desc.PetName; newPoint.desc = currentDesc; return newPoint; If you rerun the application once again and view the output (see below), you see that the Point returned from Clone() does copy its internal reference type member variables (note the pet name is now unique for both p3 and p4). ***** Fun with Object Cloning ***** Cloned p3 and stored new Point in p4 Before modification: p3: X = 100; Y = 100; Name = Jane; ID = 51f64f25-4b0e-47ac-ba35-37d263496406 p4: X = 100; Y = 100; Name = Jane; ID = 0d3776b3-b159-490d-b022-7f3f60788e8a Changed p4.desc.petName and p4.X After modification: p3: X = 100; Y = 100; Name = Jane; ID = 51f64f25-4b0e-47ac-ba35-37d263496406 p4: X = 9; Y = 100; Name = My new Point; ID = 0d3776b3-b159-490d-b022-7f3f60788e8a To summarize the cloning process, if you have a class or structure that contains nothing but value types, implement your Clone() method using MemberwiseClone(). However, if you have a custom type that maintains other reference types, you might want to create a new object that takes into account each reference type member variable, in order to get a “deep copy.”  Source Code The CloneablePoint project is located under the Chapter 8 subdirectory. 312