Debugging a foreach loop in C#: what iteration is this?

Viewed 20238

Other than setting a debug variable and incrementing it every time you start the foreach, when you break in with the Visual Studio debugger connected, is there a way to tell that this is the Xth time through the loop?

I guess this would be a feature of Visual Studio if anything, not something that would be added to the compiled code.

11 Answers

You can also use Visual Studio's Immediate Window, which allows you to write C# expressions against any variables in scope while debugging. Use the List.IndexOf() method, like so:

querying the foreach iteration index in the Immediate Window

Here's how I do it [in VS 2017] :

  1. Set a break point inside the foreach loop
  2. Right click the break point and select 'Actions'
  3. In the text box, enter the following: $FUNCTION {list.Items.IndexOf(item)} where 'list' is the name of your list and 'item' is the current item
  4. Continue running the code and watch the output window

Hit count in Visual Studio 2017:

  1. Set the breakpoint anywhere inside the foreach loop.
  2. Right-click your breakpoint and click "Conditions...".

Conditions

  1. Check "Conditions" box, switch dropdown to "Hit Count" and edit your Hit Count settings.

Hit Count

  1. On halt, hover the breakpoint to see your settings and the Hit Count reached so far.

Hover

  1. Don't forget that your hit count is not automatically reset to zero when you enter the loop for the 2nd time in the same session. ;-) But you can reset it manually:

Reset

Related