Thursday, 15 August 2013

c# - Create new instance of a class when copying it -



c# - Create new instance of a class when copying it -

i have class :

public class dog{ public dog(string name, int age){ name = name; age = age; } public string name { get; set; } public int age { get; set; } }

then create instance of class

dog jake = new dog("jake", 3);

and when seek re-create class , alter properties like

dog buster = jake; buster.name = "buster";

when this, name in jake alter too

how can avoid ?

note class i'm working contains much properties , create much easier me if can re-create class , alter 1 property want.

this happen because of way memory works in c#. each class object pointer object in memory - when assign 1 variable another, you're still using same pointer and, thus, modifying same info when create alter 1 object.

technically speaking, if made objects structs, re-create around fine, because structures values types , pass copies. this, however, highly inadvisable because limits usage, particularly polymorphism, , bad thought memory management of objects lots of members.

the best way solve implement function on class dog allows re-create info new dog object. thus, call

dog buster = jake.clone(); buster.name = "buster";

and in clone, re-create properties current dog object new dog object.

edit: going c++ roots, it's mutual implement "copy constructor" takes parameter of same type in , makes deep copy. ie

dog jake = new dog() { name = "jake" }; dog buster = new dog(jake) { name = "buster" };

note: above syntax uses curly brackets, allows set properties , fields class create it. while technically compiler sugar, @ making instantiation calls lot more succinct

c# class clone

No comments:

Post a Comment