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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With