When debugging I sometimes find the need to compare object references in the watch window to see if two variables are actually referencing the same object.
With C++ and pointers this is easy, but is there any way of doing this with C# references?
The Compare-Object cmdlet compares two sets of objects. One set of objects is the reference, and the other set of objects is the difference. Compare-Object checks for available methods of comparing a whole object.
Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity. For example, the expression obj1==obj2 tests the identity, not equality.
To open the Autos window, while debugging, select Debug > Windows > Autos, or press Ctrl+Alt+V > A. To open the Locals window, while debugging, select Debug > Windows > Locals, or press Alt+4. This topic applies to Visual Studio on Windows.
There is actually a built in feature for comparing objects in the Watch window that doesn't require you to call any functions directly. It's in the right click menu as "Make Object ID"
It will mark the object with an ID, and then you can add a second object and mark it with an id as well. If those object are the same reference, then they will have the same ID. This allows you to see if/when they change as you are debugging.
object.ReferenceEquals(objA, objB)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With