public override object clone() { MyClass clon = new MyClass(); clon.i = this.i; clon.str = this.str; //clon.id = this.id; // passive clonning clon.id = clon.GetHashCode(); // smart clonning return clon; #region another way MyClass clon2 = (MyClass)this.MemberwiseClone(); clon2.id = clon2.GetHashCode(); return clon2; //or //return this.MemberwiseClone(); #endregion }
static void Main(string[] args) { MyClass m1 = new MyClass(); MyClass2 m2 = new MyClass2(); MyClass3 m3 = new MyClass3(); Console.WriteLine(m1.GetHashCode() + " " + m1.id); Console.WriteLine(m2.GetHashCode() + " " + m2.id); Console.WriteLine(m3.GetHashCode() + " " + m3.id); Console.WriteLine("-----------------------"); m1 = (MyClass)m1.clone(); m2 = (MyClass2)m2.clone(); m3 = (MyClass3)m3.Clone(); Console.WriteLine("-----------------------"); Console.WriteLine(m1.GetHashCode() + " " + m1.id); Console.WriteLine(m2.GetHashCode() + " " + m2.id); Console.WriteLine(m3.GetHashCode() + " " + m3.id); }