Setting conditional breakpoints using object ids


In native code, its sometimes useful to set a breakpoint condition so that a breakpoint will only stop for a particular instance of an object. To do this, I simply use the address of the object:



this == (CMyObject*)0x10fc10


In managed code, the garbage collector moves objects around, so even if you were writing in a language that had great support for pointers, setting a conditional breakpoint this way is probably useless. Instead, you can do this using object ids.


Step #1: Make an Object ID. To do this, get the object that you want to use in your condition into the watch window. Then right click on this object and invoke the ‘Make Object ID’ context menu. The watch window output will now include ‘{1#}’:



+  this {cswin.Form1, Text: Form1} {1#} cswin.Form1


The ‘1#’ indicates that this is the first object ID. Each object ID created will get a new object ID (2#, 3#, etc). There is more documentation under ‘Object Identity’ on MSDN.


Step #2: Set conditional breakpoint. Right click on your breakpoint and click ‘Condition…’, and set it to what you want. For example:



this == 1#


Happy debugging.


Comments (15)

  1. luisguerrero18@hotmail.com says:

    it’s great, but when i stop debugging, visual studio doesn’t remember my Object ID, so always have to set object ID to do condicional debug

  2. Good point. This is because the debugger has no way to presist object ids accross debug sessions. Managed code doesn’t have an ‘allocation identifier’ like native code does.

  3. Jeff Stong says:

    Many times I’ve made use of the ability to set a conditional breakpoint based on the address of object…

  4. John Schroedl says:

    Great tip.  I didn’t know about object id.

    John

  5. Kim Gräsman says:

    One issue we see with using the address is that memory blocks are reused frequently, so 0x12345678 doesn’t necessarily point to the _same_ object, just to an object of the same type created on the same memory space.

    I’m curious, does the object ID feature handle this somehow?

    Thanks!

  6. Kim Gräsman says:

    Oh, and does it work for both native and managed code?

  7. Object IDs work like a WeakReference. So they will always indicate the same object.

    This only works with managed code.

  8. Wooseok Seo says:

    Great tip.

    Many thanks!

    Wooseok.

  9. Just found out about a neat way to keep track of managed object references while debugging. Check out

  10. Some cool stuff happening in the testing world: * Project white seems like a nice takeoff on winforms

  11. Links of the Week #25 (week 8/2008)

  12. Zunanji viri says:

    Development Top-10 Application-Design Mistakes – How not to design your UI. It's hard not to nod

  13. You’ve been kicked (a good thing) – Trackback from DotNetKicks.com

  14. Interesting blog post describing some of the shortcomings of ASP.MVC Anotherblog post, this time about