27

When debugging, I was expecting two different classes to be using the same instance of an object. All of the properties were the same for these two objects, but they were two different instances. Is there a way to tell that in the VS debugger?

In order to tell for sure, I was able to add a field to the class:

private string someId = Guid.NewGuid().ToString();

Then, when debugging, I could at least look at that field for each of the two instances. Is there a better way that wouldn't involve having to create this dummy ID field?

Bob Horn
  • 33,387
  • 34
  • 113
  • 219
  • 4
    Object.ReferenceEquals(obj1, obj2) – Peter Ritchie Mar 22 '13 at 20:01
  • 3
    @PeterRitchie So how do you do this in the debugger? The objects, that need to be checked, are in two different classes. – Bob Horn Mar 22 '13 at 20:09
  • 2
    Shift+F9, type in "Object.ReferenceEquals(obj1, obj2)" and press Reevaluate or Add Watch. Or just type "Object.ReferenceEquals(obj1, obj2)" in the Name column in the Watch window. – Peter Ritchie Mar 22 '13 at 20:14
  • 1
    possible duplicate of [Uniquely Identifying Reference Types in the Debugger](http://stackoverflow.com/questions/4251450/uniquely-identifying-reference-types-in-the-debugger) – Ian Goldby Jul 30 '15 at 14:33

3 Answers3

55

When debugging, in the Locals window, right-click on the instance and select "Make Object ID".

This will add number that is unique for this instance which is displayed whenever you see this instance in the debugger (in tool-tips as well as in the watch window).

enter image description here

enter image description here

Bob Horn
  • 33,387
  • 34
  • 113
  • 219
Wolfgang
  • 3,460
  • 3
  • 28
  • 38
  • Thanks, but I don't see "Make object ID" when I right-click on the variable when debugging. – Bob Horn Mar 22 '13 at 20:16
  • Got it! You have to do it in your Locals window: http://blogs.msdn.com/b/zainnab/archive/2010/03/04/make-objectid-vstipdebug0015.aspx. Excellent tip! Thanks! – Bob Horn Mar 22 '13 at 20:18
  • When you use this option, what happens when the object is disposed? I am debugging some thing related to EF DbContext and it seems that these objects stay in the Locals window, even though (I hope) they were already disposed... – Bartosz Jul 12 '17 at 19:17
5

Object.Equals Method (Object, Object)

Edit: To check reference equality use ReferenceEquals

Edit 2: While Debugging, Go to debug menu, windows --> immediate window (intellisense should work here) and ?Object.ReferenceEquals(obj1, obj2)

A G
  • 21,087
  • 11
  • 87
  • 112
2

In addition to the answers above, you can also compare pointers. If you have two objects obj1 and obj2, you can check (e.g. in Watch Window) their addresses with: &obj1 and &obj2.

Note that objects may be moved around by the .NET runtime, so two address checks of the same object separated with some code execution in between may result in different addresses.