Object.MemberwiseClone Method Creates a shallow copy of the current Object. : System Object Method « Development Class « C# / C Sharp






Object.MemberwiseClone Method Creates a shallow copy of the current Object.

 

using System;

public class IdInfo
{
    public int IdNumber;

    public IdInfo(int IdNumber)
    {
        this.IdNumber = IdNumber;
    }
}

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;
    }
}

public class Example
{
    public static void Main()
    {
        Person p1 = new Person();
        p1.Age = 42;
        p1.Name = "Sam";
        p1.IdInfo = new IdInfo(6565);

        Person p2 = (Person) p1.ShallowCopy();
    }
}

   
  








Related examples in the same category

1.illustrates some of the System.Object class methodsillustrates some of the System.Object class methods
2.System Functions: LogOff, Restart, Shutdown, Hibernate, Standby
3.The Point class is derived from System.Object.
4.Object.Equals Method Determines whether the specified Object is equal to the current Object.
5.override Equals method
6.Build Equals method by using the Equals method from member variables
7.ValueType.Equals
8.Object.GetType Method Gets the Type of the current instance.
9.Object.ReferenceEquals Method Determines whether the specified Object instances are the same instance.
10.Object.ToString Method Returns a String that represents the current Object.