Reputation: 2566
Assuming I have a reference type class Foo { }
and I am passing the reference of an instance of it to two separate methods
void Main()
{
Foo f = new Foo();
Bar(f);
Baz(f);
}
void Bar(Foo f)
{
// ...
}
void Baz(Foo f)
{
// ...
}
how can I find out whether the objects I see in Bar
and Baz
point to the same object in memory while I am debugging? I guess looking at GetHashCode()
is not necessarily an indicator, because I could have overridden GetHashCode()
in Foo
to always return 0
for instance.
Independently of the fact that it's impossible in C# and my little knowledge of pointers, I guess looking at the address the references point to would give me the certainty.
What options do I have?
Upvotes: 0
Views: 81
Reputation: 15227
There is a little feature in Visual Studio debugger that exactly suits your needs without having to implement something.
Just set the break points on your methods. When one of the break points hits, add the object you're interested in (the f
parameter of Foo
type) into the Watches list. You can indeed find that object in the Autos or Locals windows too.
Then do the trick: right click on the object entry in the list and select Make Object ID. A numerical ID appears to the right of the object's value in the list.
Now continue debugging. When your second break point hits, you'll see in your Locals, Autos and maybe Watches windows that the f
object appears with the same ID. That means - it's the same object instance. If there were no ID or it were different, then this would be a different instance of Foo
.
Upvotes: 2