Deep Copy in C#
<p>MSDN gives this example of a deep copy (<a href="http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx</a>)</p>

<pre><code>public class Person 
{
    public int Age;
    public string Name;
    public IdInfo IdInfo;

    public Person ShallowCopy()
    {
       return (Person)this.MemberwiseClone();
    }

    public Person DeepCopy()
    {
       Person other = (Person) this.MemberwiseClone(); 
       other.IdInfo = new IdInfo(this.IdInfo.IdNumber);
       return other;
    }
}
</code></pre>

<p>But, doesn't a new Person object have to be instantiated, and then returned? For example, is this code below acceptable/equal/inferior to the code above for performing a deep copy?</p>

<p>As I understand the MemberwiseClone() method, it just performs a shallow copy, i.e. copies values/references from copied object to new object. This results in a shallow copy since the memory references are equal, i.e. the references point to the same objects.</p>

<pre><code>public class Person 
{
    public int Age;
    public string Name;
    public IdInfo IdInfo;

    public Person ShallowCopy()
    {
       return (Person)this.MemberwiseClone();
    }

    public Person DeepCopy()
    {
       Person other = new Person(); // difference
       other.IdInfo = new IdInfo(this.IdInfo.IdNumber);
       return other;
    }
}
</code></pre>
