To create a clone use this.MemberWiseClone() methods . It is defined in System.Object class. It creates the shallow copy of the current System.Object.
Code…
class XYZBuilder { private int _X=10;public int X { get { return _X; }set { _X = value; } } private int _Y=15;public int Y { get { return _Y; }set { _Y = value; }
}
private int _Z=20;
public int Z{ get {return _Z;}
set {_Z = value;}
}public XYZBuilder Clone()
{return (XYZBuilder)this.MemberwiseClone(); }
}
class TestClone { public void TestCloning() {
XYZBuilder XYZObject1 = new XYZBuilder();XYZObject1.X = 40;XYZObject1.Y = 60;XYZObject1.Z = 90;
//make a clone
XYZBuilder XYZObject2 = XYZObject1.Clone();
//change the values in xyzobject1 and see what happens
XYZObject1.X = 100;XYZObject1.Y = 100;XYZObject1.Z = 100;
//show values MessageBox.Show(XYZObject2.X.ToString());
MessageBox.Show(XYZObject2.Y.ToString());
MessageBox.Show(XYZObject2.Z.ToString());
}
} |