What is the method MemberwiseClone() doing?

Technology CommunityCategory: C#What is the method MemberwiseClone() doing?
VietMX Staff asked 3 years ago

The MemberwiseClone() method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object.

  • If a field is a value type, a bit-by-bit copy of the field is performed.
  • If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.

Consider:

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(IdInfo.IdNumber);
       other.Name = String.Copy(Name);
       return other;
    }
}