c# - why is my passed object getting edited -
i pass 'global' object param method. init new instance of object , set equal original, in head have 2 instances of object.
why when change second instance first instance change? never used 'ref'.
namespace mynamespace { public class myclass { private myobjectclass myglobalinstance; public void mymethod() { dosomething(myglobalobject); } private string dosomthing(myobjectclass myobjectinstance) { myobjectclass newobject = myobjectinstance; newobject.variable1 = "boo"; //this seems change both newobject.variable1 required , myobjectinstance.variable1 , calling classes object } } }
you copying reference object thats problem. create object same properties use memberwiseclone:
public class globalobject { public globalobject getcopy() { return (globalobject)memberwiseclone(); } }
but have understand difference between shallowcopy , deepcopy
your code this:
namespace mynamespace { public class myclass { private globalobject myglobalinstance; public void mymethod() { dosomthing(myglobalobject); } private string dosomthing(globalobject myobjectinstance) { globalobject newobject = myobjectinstance.copy(); newobject.variable1 = "boo"; } } }
Comments
Post a Comment