Search code examples
c#shallow-copy

Why isnt this object null after a shallow copy?


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


Solution

  • 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.