How to determine the reference equality of two variables in different areas?

Let's say you are debugging. At some point, you are in method A, which has a foo parameter of type Foo . Later you are in method B, which also accepts a parameter foo of type Foo .

These two variables may be identical instances of Foo , but how do you say this? Since they are in different areas, you cannot call ReferenceEquals() . Is there a way to get the actual memory location pointed to by the variables so that you can determine if they are an instance?

+7
source share
4 answers

I believe that you can use the Make Object ID function. More information about this can be found here , but summarize:

  • Install BreakPoint in your code, where you can go to the object variable that is in the area.
  • Run your code and leave it in BreakPoint.
  • In the "Locals" or "Auto" window, right-click the object variable (pay attention to the "Value" column) and select "Make Object Identifier" in the context menu.
  • You should now see the new identification number (#) new in the Value column.

After you β€œmark” the object, you will see the assigned identifier in the second Foo call.

+6
source

In the debugger, you can save the reference to the object in the first method to a static field, and then compare the variable in the second method with the static field.

+1
source

well, you can get a pointer to your variable, but for this you need to run an unsafe block.

once you are "unsafed", you can declare a pointer to your Foo as follows:

 Foo* p = &myFoo; 

this has already been discussed here in SO:

C # memory address and variable

0
source

As a development proposal for Mark Cidade, when inside the first method, enter the following in the next window:

 var whatever = foo; 

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

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

The test result will be displayed in a direct window.

However, the CodeNaked suggestion is better.

0
source

All Articles