Search code examples
c#debuggingpropertiesmemory-addresswatch

Why can't I see the memory addresses of some objects?


I have an object model, based on TCP Connections, which belong to Connections, which belong to Managers. It seems like two TCP Connections are different, which I can see, but when I try to see the same for the Connections they belong to, I get error message CS0211: Cannot take the address of the given expression. Do anybody know why and how I can handle this?

Watch window content for both TCP Connections:

&connectionManager.Connection.TcpConnection  0x00007fe80035f670
&Connection_For_Message.TcpConnection        0x00007fe70042bf08

=> both TCPConnections are in another memory address, so they are clearly different (although all their values, properties and attributes are equal).

When asking the same for the Connections, this does not work:

&connectionManager.Connection  error CS0211: Cannot take the address of the given expression    
&Connection_For_Message        0x00007fe700375230

Why is that?

For your information: when I ask for connectionManager.Connection (not the address, just the data), everything is ok.

Thanks in advance


Solution

  • Retrieving an object address in different parts of the code may be misleading because objects can be moved if GC runs in the middle. The simplest way to go is to check the object's Hash Code by calling GetHashCode() method. If you get different numbers, two objects are guaranteed to be different. But equal Hash Codes don't 100% mean that two references point to the same object. In that case, you can use a temporary hack and store the first object in public static variable, then, when the code reaches the second object, use Object.ReferenceEquals(obj1, obj2) as suggested by @KlausGütter in comments.