Monday, June 24, 2013

ICloneable

I want to create an object 'b' with the same values as the original object 'a'. At runtime, the values on 'b' keep changing without altering the values of 'a'. Once successful, 'a' adopts the new values of object 'b'. Otherwise, object 'a' retains its original values.

void Main()
{
    bool success = false;

    Object a = new Object();
    Object b = (Object)a.Clone();
           
    b.anyVal = "BBB"; //at runtime
    if(success ==  true) a = (Object)b.Clone();
}

class Object : ICloneable
{
    public string anyVal { get; set; }
   
    public Object() { anyVal = "AAA";}

    public object Clone() { return this.MemberwiseClone(); }
}