Christian said:
what's the use of MemberwiseClone() ? It only performs a shalow copy as does
the assignment of one object to another :
myObj1 = myObj2
No, there's a big difference.
myObj1 = myObj2.Clone();
- Now the values of myObj1 and myObj2 are references to different
objects. They happen to have the same values at this point in time, but
they needn't in the future.
myObj1 = myObj2;
- Now the values of myObj1 and myObj2 are references to the same
object. Any change made to the object via either variable is visible
via the other variable.
Here's a small test program to show the difference:
using System;
public class Test : ICloneable
{
string name;
public string Name
{
get { return name; }
set { name = value; }
}
static void Main()
{
// Set up the initial object
Test t1 = new Test();
t1.Name = "Bob";
Console.WriteLine ("Using Clone()");
Test t2 = (Test)t1.Clone();
t2.Name = "Fred";
Console.WriteLine ("t1.Name={0}", t1.Name);
Console.WriteLine ("t2.Name={0}", t2.Name);
Console.WriteLine ("Using assignment");
Test t3 = t1;
t3.Name = "Fred";
Console.WriteLine ("t1.Name={0}", t1.Name);
Console.WriteLine ("t3.Name={0}", t3.Name);
}
public object Clone()
{
return MemberwiseClone();
}
}