Lijin John Lijin John - 27 days ago 8
C# Question

What is the difference between MemberwiseClone() and Assigning a Reference type in C#?

If i have a code like this

class Student
{
public string RollID { get; set; }
}
class Person
{
public Student student { get; set; }
public string Address { get; set; }
public string Name { get; set; }
public Person Clone()
{
return (Person)this.MemberwiseClone();
}
}
class Client
{

static void Main()
{
Student s1 = new Student();
s1.RollID = "151";
Person p1 = new Person();
p1.Address = "bombay";
p1.Name = "foo";
p1.student = s1;

Person p2 = p1.Clone();
p2.student.RollID = "1558";

Person p3 = p1;
p3.student.RollID = "454";
}
}


and when I change the value of p2 it changes the value of p1 as well and I get the same result when I change the value of the Object p3. My question is if both the logic does the same thing then what is the real difference between assigning and using
MemberwiseClone()
method. Is there any other advantage if i use the
MemberwiseClone()
method?

Answer

The issue here is that you're doing a "deep" update on a shallow copy. If you changed p2.Address, it would not affect p1.Address; but if you change p3.Address it will change affect p1.Address.

But since p1 and p2 share a reference to a single Student, changing the RollId affects everyone.

Variable P1 ---->  <PERSON OBJECT 1>
                   |       .Address = 123 Elm St.
Variable P3 ---->  |
                   |       .Student  ----> <STUDENT OBJECT 1>
                   |_______________        |
                                           | .RollId // one value for all
Variable P2 ---->  <PERSON OBJECT 2>       |
                   |       .Address = ...  |
                   |       .Student  ----> |_________________
                   |_______________
Comments