title: ICloneable Interface
body: <p>This relates to the "Watson et al: Beginning Visual C# Chapter 10: exercise 4":
  Implement the ICloneable interface on the People class to provide deep copying capability</p>
  
  <pre><code>class People : DictionaryBase: ICloneable
  
      public void DictAdd(Person newPerson)
      {
          Dictionary.Add(newPerson.Name, newPerson);
  
      public object Clone()
      {
  
          People newPeople = new People();
  
  
          foreach (Person myPerson in Dictionary.Values)
          {
              Person ClonePerson = (Person)myPerson.Clone();
              newPeople.DictAdd(ClonePerson);
          }
  
          return newPeople;
      }
  </code></pre>
  
  <p>In the Person class we have:</p>
  
  <pre><code>        public object Clone()
      {
          Person newPerson = new Person();
          newPerson = (Person)newPerson.MemberwiseClone();
          newPerson.Age = age;
          newPerson.Name = name;
          return newPerson;
  
      }
  </code></pre>
  
  <p>To test it in Program.cs:</p>
  
  <pre><code>People clonedPeople = (People)PeopleCollection.Clone();
  
          PeopleCollection.Remove("Mick");
          myPerson1.Name = "Jock";
          myPerson1.Age = 13;
          PeopleCollection.DictAdd(myPerson1);
  
  
          Console.WriteLine("In the current collection \"Mick\" is now: \"{0}\" and his age is: {1}", myPerson1.Name, myPerson1.Age);
          Console.WriteLine("But \"Mick\" should remain in the original collection, now cloned.");
          foreach (DictionaryEntry p in clonedPeople)
          {
              Console.WriteLine();
              Console.WriteLine("myPerson Name: {0} myPerson.Age: {1}", ((Person)p.Value).Name, ((Person)p.Value).Age);
          }
  </code></pre>
  
  <p>This works, and the original values of "Mick" are preserved.
  But the question is to the point of implementing ": ICloneable" on the Person and People class in the first place. The code works the same with or without it.</p>
  
  <p>A related question is to the efficacy of what they call running a "recursive" implementation of ICloneable in their example</p>
  
  <pre><code> public class Content
   {
   public int Val;
   }
   public class Cloner: ICloneable
   {
   public Content MyContent = new Content();
   public Cloner(int newVal)
   {
   MyContent.Val = newVal;
   }
       public object Clone()
       {
       Cloner clonedCloner = new Cloner(MyContent.Val);
       return clonedCloner;
       }
   }           
  </code></pre>
  
  <p>Have attempted miserably to get this recursion to work, but all we end up with is a StackOverflow. Short of using a global/static variable to quit the loop, does there exist an elegant way to implement this "recursively?"</p>