I have a System.Collections.Generic.Dictionary object in my code and am trying to view its contents while stopped at a breakpoint in the Visual Studio debugger. The Dictionary class in .NET of course contains a list of keys and values.
If I right-click on the loaded object, and try to drill down into its contents, I seem to get into an infinite loop. For instance, if I'm trying to see the contained keys, I expand the Keys element, which shows me a count, and another collection called "Non-Public members". I expand the latter, and get another dictionary object, which has a Keys element, which I can expand to get another instance of "count" and "Non-Public members", which I can expand, etc., etc.:
Using QuickWatch gives me the same result, so how do I actually view the keys contained in the object?
When stopped in the debugger hover the mouse cursor over the variable you want to look at. The DataTip will appear showing you the value of that variable. If the variable is an object, you can expand the object by clicking on the arrow to see the elements of that object.
Add a variable to a Watch windowRight-click the variable in the data tip, and select Add Watch. The variable appears in the Watch window. If your Visual Studio edition supports more than one Watch window, the variable appears in Watch 1.
I know this issue is fixed in later versions of Visual Studio. However, for some of us who are stuck in an older version of VS here is a quick fix to see the keys of a dictionary.
Let's say we have a dictionary named 'dict'. We need the keys to see the values. So in a watch window do this:
dict.Keys.ToList()
That will allow you to drill down into the list and see the keys.
If you know the index of the key you want to you do the following:
dict.Keys.ToList()[1]
This will display the key at index 1.
Now you can take that key and see what the value is with:
dict[dict.Keys.ToList()[1]]
Of course you can replace the index into the keys list with the actual key value in another watch line if that is easier.
EDIT: In addition, it is also possible to see the entries of a dictionary with the following in the watch window:
'dict.entries'
This will give you a list of entries to look through. Each entry will have a 'key' and 'value' property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With