Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 756
Matt Avatar asked Jul 20 '10 18:07

Matt


People also ask

What is foreach loop in C?

There is no foreach in C. You can use a for loop to loop through the data but the length needs to be know or the data needs to be terminated by a know value (eg. null).

Which is faster for or foreach?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.


2 Answers

Set a breakpoint inside the loop, then right click on the breakpoint to set the conditions. You can also right click to see the hit count while debugging and reset it if you want. You can set a boolean expression that is evaluated when the breakpoint hits to conditionally break (or just pass over).

like image 150
Garo Yeriazarian Avatar answered Sep 19 '22 19:09

Garo Yeriazarian


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

like image 42
Jeremy Deal Avatar answered Sep 20 '22 19:09

Jeremy Deal