Made one instance of a class equal to another. – How to cancel that?

Your code:

myclass a = new myclass();
a.integer = 1;

myclass b = new myclass();
b.integer = 2;

a = b;

//here I need code to disconnect them

a.integer = 1;

Text = b.integer.ToString();
//I need b.integer to still be = 2

enter image description here

If you keep around a reference:

myclass a = new myclass();
a.integer = 1;

myclass b = new myclass();
b.integer = 2;

var c = a; //Keep the old a around
a = b;

//here I need code to disconnect them
a = c; //Restore it.

a.integer = 1;

Text = b.integer.ToString();
//It's still 2 now.

enter image description here

Variables are labels to the objects, not the objects themselves. In your case, the original a no longer has a reference to it so even though it exists, there’s no way to access it. (and it’ll cease to exist whenever the garbage collector gets around to getting rid of it unless there are other references to it)

If it helps, think of it this way, when you say a = b or a = new myclass() you are moving the line where a is pointing. When you say a.integer = 1, the . is kind of like saying follow the line a is pointing to, then change the destination.

Leave a Comment