1

Is there a way in .NET (C#) when using the debugger to know what collections an object is currently in.

I have a situation where class instances are moving in and out of different Lists and Arrays and am trying to track down which collections at any point in time it is currently in. i.e. when i hit a breakpoint.

The only solution I can think of is coding some kind of tracker class. Was hoping the debugger might have a way of tracing this.

Edit: I guess its kind of like the way you can expand a collection in the debugger and see the members, except I'd like to do the reverse.

Thanks.

Matt
  • 13
  • 3

2 Answers2

1

It sounds like you would benefit from using the observer pattern, which creates a "one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically". Basically, you have an object that receives a notification whenever an item gets added to a collection.

.NET 4 has a built in implementation of this pattern. Check out Observer Design Pattern in .NET.

Interface Documentation:

It also may be worthwhile to look at the ObservableCollection<T> class, and see if that would provide the functionality you need. It is available in .NET 3.

smartcaveman
  • 41,281
  • 29
  • 127
  • 212
  • Thanks caveman, ObservableCollection does appear to do what I need. I will give it a shot. – Matt Apr 04 '11 at 06:32
0

I don't believe there's anything like this built-in, but it would be pretty easy to create. Just add expressions to the Watch window, one per collection.

Or create a single function in your code that searches the collections and returns, say, an array of strings (collection names) - and call that function from the Watch window.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810