Use MemberwiseClone method to clone object : MemberwiseClone « Class « C# / CSharp Tutorial






using System;

class MyValue
{
    public MyValue(int count)
    {
        this.count = count;
    }
    public int count;
}
class MyObject
{
    public MyObject(int count)
    {
        this.contained = new MyValue(count);
    }
    public MyObject Clone()
    {
        Console.WriteLine("Clone");
        return((MyObject) MemberwiseClone());
    }
    public MyValue contained;
}
class MainClass
{
    public static void Main()
    {
        MyObject my = new MyObject(3);
        MyObject myClone = my.Clone();
        Console.WriteLine("Values: {0} {1}", my.contained.count, myClone.contained.count);
        myClone.contained.count = 1;
        Console.WriteLine("Values: {0} {1}", my.contained.count, myClone.contained.count);
    }
}
Clone
Values: 3 3
Values: 1 1








7.50.MemberwiseClone
7.50.1.Create a clone using the Object.MemberwiseClone method because the Employee class contains only string and value types
7.50.2.Use MemberwiseClone method to clone object
7.50.3.Perform a memberwise clone of myEmployee using the Employee.Copy() method