Search code examples
c#pointersdebuggingdynamic-memory-allocationidentity

Am I always dealing with the same object?


I'm working on a TCP socket related application, where an object I've created refers to a System.Net.Sockets.Socket object. That latter object seems to become null and in order to understand why, I would like to check if my own object gets re-created. For that, I thought of the simplest possible approach by checking the memory address of this. However, when adding this to the watch-window I get following error message:

Name    Value
&this   error CS0211: Cannot take the address of the given expression

As it seems to be impossible to check the memory address of an object in C#, how can I verify that I'm dealing with the same or another object when debugging my code?


Solution

  • In C#, objects are moved during garbage collection. You can't simply take the address of it, because the address changed when the GC heap is compacted.

    Dealing with pointers in C# requires unsafe code and you leave the terrain of safe code, basically making it as unsafe as C++.

    You can use a debugger like , which displays the memory addresses of objects - but they will still change when GC moves them around.

    If you want to see if a new instance of your class gets created, why not set a breakpoint in the constructor?