This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.


Visual Studio Watches and Object IDs

Watches can be added in Visual Studio to allow the values of variables and expressions to be viewed and automatically refreshed when debugging. Usually watches are limited to local variables. With object IDs, values can be monitored even if out of scope.


In recent articles we've looked at some of the debugging windows in Visual Studio. These allow you to monitor the state of local variables whilst debugging your code. With the Locals and Autos windows in-scope values are displayed but are removed from the list when they go out of scope. The watches windows generally show items when they out of scope but the values do not refresh and cannot be edited.

When debugging code in some languages you can add a watch based upon the address of a variable, rather than its name. In this manner you can monitor the values as if they were in scope. If you are using C#, you cannot watch an address but you can assign a unique, temporary object ID to an object and watch this ID. When the variable goes out of scope, the object ID does not. This means that you can continue to monitor its value, refresh and edit it where appropriate.

The image below shows an example watch window. Here the testVector variable has been watched but the variable is out of scope so is disabled in the grid. Note that the Value column for the testVector object has an object ID (1#). The second watch refers to this object ID directly so the rows are not disabled and can be monitored and edited as required.

Visual Studio watching and object ID

Creating an Object ID

To watch a variable using an object ID, first add a watch to the variable itself. Right-click the watch in the grid and choose the "Make Object ID" option from the context-sensitive menu. This will create a new unique ID and show it in the watch window. To create a watch of the object ID, type the ID into a new grid row, as shown in the above image. You will find that the watch continues to function normally, even when the underlying variable is out of scope.

NB: You can only create object IDs for objects. If you right-click a watch for a value type, the Make Object ID menu is not available.

5 August 2011