There may be many instances where we have to clone a object. For example, we open the object for edit in a form and after few modifications, if the user decides to abandon changes/cancel modifications and if we are using the main object to do all the changes, it would be a disaster.
Cloning is a way out of it. I remember a time when we had to write another clone method to achieve the cloning of object. With C#, its 2 lines of code!
Your class can be like this..
public class myclass
{
public int id { get; set; }
public string name { get; set; }
public string value { get; set; }
}
Now to make it clone-able change it this way…
public class myclass :ICloneable
{
public int id { get; set; }
public string name { get; set; }
public string value { get; set; }
public object Clone() { return this.MemberwiseClone(); }
}
Try this..
myclass a = new myclass();
a.id = 1;
a.name = "asdf";
a.value = "qwer";
myclass b = a.Clone() as myclass;
b.value = "zxcv";
myclass c = a;
Console.Write(a.value + " " + b.value + " " + c.value) ;
output will be
qwer zxcv qwer
Simple isn’t it?
More ways of cloning objects are shown here