Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object assignment

Tags:

c#

I have a scenario like:

MyClass obj1 = new MyClass();
............//some operations on obj1;
MyClass obj2 = new MyClass();
obj2 = obj1;

I have the following problem: if I modify any parameter, it is affected in both objects (as both refer to same location) - but, when I modify obj2 parameter, it should not modify that parameter value in obj1 (i.e. means both should not point to same location). How can I do that? Please help me. I can't clone here as myclass is not implementing ICloneable and I can't modify myclass. if I clone by serializing and deserializing, will it be a Deep clone?

like image 590
sandhya Avatar asked Jan 23 '23 09:01

sandhya


2 Answers

Make your MyClass implement ICloneable and use

MyClass obj1 = new MyClass();
...
MyClass obj2 = obj1.Clone();

If MyClass is not clonable, you need to look up all characteristic values in obj1 and copy them to obj2, e.g.

myclass obj2 = new myclass();
obj2.color = obj1.color; // .Clone();
obj2.size = obj1.size;
obj2.numberOfLimbs = obj1.numberOfLimbs;
// etc.
like image 182
kennytm Avatar answered Feb 01 '23 01:02

kennytm


The thing to remember with object assignment is the difference between variables and objects.

In your example, obj1 and obj2 are variables. Variables can refer to objects, but they are not objects themselves.

What your code does is, at the end, tell both obj1 and obj2 to refer to the same object.

What you want to do is make a new object - which, as others pointed out, is most easily done through the ICloneable interface.

like image 37
kyoryu Avatar answered Feb 01 '23 03:02

kyoryu