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


if have code

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 change value of p2 changes value of p1 , same result when change value of object p3. question if both logic same thing real difference between assigning , using memberwiseclone() method. there other advantage if use memberwiseclone() method?

the issue here you're doing "deep" update on shallow copy. if changed p2.address, not affect p1.address; if change p3.address change affect p1.address.

but since p1 , p2 share reference single student, changing rollid affects everyone.

variable p1 ---->  <person object 1>                    |       .address = 123 elm st. variable p3 ---->  |                    |       .student  ----> <student object 1>                    |_______________        |                                            | .rollid // 1 value variable p2 ---->  <person object 2>       |                    |       .address = ...  |                    |       .student  ----> |_________________                    |_______________ 

Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -