David
David

Reputation: 16120

How to determine reference equality of two variables in different scope?

Let's say you are debugging. At one point you are in Method A, which has a parameter foo of type Foo. Later on you are in Method B, which also takes a parameter foo of type Foo.

These two variables may well be the same Foo instance, but how do you tell? Because they are in different scope, you cannot call ReferenceEquals(). Is there some way you can obtain the actual memory location the variables point to so that you can tell if they are the instance?

Upvotes: 7

Views: 168

Answers (4)

David
David

Reputation: 16120

As a development of Mark Cidade's suggestion, when inside the first method type the following into the immediate window:

var whatever = foo;

Then, when in the second method, type the following:

bool test = object.ReferenceEquals(whatever, foo);

The immediate window will display the result of the test.

However, CodeNaked's suggestion is better.

Upvotes: 0

CodeNaked
CodeNaked

Reputation: 41393

I believe you can use the Make Object ID feature. More information on this can be found here, but to summarize:

  1. Set a BreakPoint in your code where you can get to an object variable that is in scope.
  2. Run your code and let it stop at the BreakPoint.
  3. In your Locals or Autos Window, right-click the object variable (note the Value column) and choose "Make Object ID" from the context menu.
  4. You should now see a new ID number (#) new in the Value column.

After you "mark" the object, you will see the assigned ID in the second call to Foo.

Upvotes: 6

Davide Piras
Davide Piras

Reputation: 44605

well you could get a pointer to your variable but this requires to run in an unsafe block.

once you are "unsafed" you can declare a pointer to your Foo like this:

Foo* p = &myFoo;

this has been already discussed here in SO:

C# memory address and variable

Upvotes: 0

Mark Cidade
Mark Cidade

Reputation: 99957

While in the debugger, you could store a reference to the object in the first method to a static field and then compare the variable in the second method to the static field.

Upvotes: 1

Related Questions