Reputation: 103
Below is my copy of spouse to client (both are same object type). Spouse is then set to null.
client = spouse; // Copying data
spouse = null;
I then pause (using a breakpoint on a different line) and check the memory of client and spouse. spouse is null, however client isn't.
Shouldn't client be null because its memory is a result of a shallow copy?
Cheers
Upvotes: 2
Views: 867
Reputation: 375
The way you are using to Shallow copy is not the proper way in C#. C# provide us a function we can use to perform a shallow copy. the function is MemberwiseClone()
.
Try this
Client = Spouse.MemberwiseClone();
Please tell me if it doesn't work for you. cheers
Upvotes: -3
Reputation: 660327
Your spouse lives at 123 Sesame Street.
You write down on a piece of paper: SPOUSE: 123 Sesame Street.
Now you write down on another piece of paper: CLIENT:. Then you copy whatever it says after SPOUSE on the first piece of paper.
Now you have two pieces of paper. One says "SPOUSE: 123 Sesame Street". The other says "CLIENT: 123 Sesame Street".
Now you erase the address on the page that says SPOUSE.
What does the page that says CLIENT now say?
Your confusion is apparent in your choice of jargon.
Do not say "makes a shallow copy". Say "copies a reference", because that's what you're doing. "Shallow" is relative without saying relative to what. Say what is really happening: the value is being copied and the value is a reference.
Do not say "this object is null". That's like saying "the car in my driveway that is not there"; it's nonsensical. A variable can contain a null reference. A reference can be a null reference; it is the reference that refers to no object. But it is not an object; it is the absence of an object.
When you make your language precise then these sorts of confusions start to drop away rapidly.
Upvotes: 13
Reputation: 27367
This doesn't happen because you are changing the value of the pointers, not the object itself.
Let's imagine this scenario:
var spouse = new Person(); //Let's say the memory address of this new person is 0x000010
Now, we have this:
Person client = null; //The pointer of client now points to 0x000000
client = spouse; //The pointer of client now points to 0x000010
spouse = null; //The pointer of spouse now points to 0x000000
//However - client has *not* changed, it still points to 0x000010
//and the object still remains in memory.
Upvotes: 4