views:

248

answers:

6

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 any 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.

+6  A: 

May be you can use breakpoint hit count. Not exactly what you want, but may be helpful.

Also is there any serious reason why you don't want to use for loop in this case.

Incognito
+10  A: 

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).

Garo Yeriazarian
+3  A: 

Have you tried using assertion in debugging? The debugger will be launched at that exact point in your code:
For example: System.Diagnostics.Debug.Assert (myValue >=0)

Hypnos
A: 

I just tried it and I did not found a way to tell. Maybe if you could give us the code inside the foreach, we could find a "trick".

Lobsterm
+1  A: 

Heres a previous SO question that seems to be what your looking for

get-index-of-current-foreach-iteration

answer quoted from that link:

Foreach is for iterating over collections that implement IEnumerable. It does this by calling GetEnumerator on the collection, which will return an Enumerator.

This Enumerator has a method and a property:

MoveNext()
Current

Current returns the object that Enumerator is currently on, MoveNext 
updates Current to the next object.

Obviously, the concept of an index is foreign to the concept of 
enumeration, and cannot be done.

Because of that, most collections are able to be traversed using an 
indexer and the for loop construct.

I greatly prefer using a for loop in this situation compared to tracking

the index with a local variable.
jumpdart
A: 

from my comment

if whatever you are iterating supports the IndexOf() method you dont have to set a debug var.

like in this example:

        foreach (var i in myList)
        {
            reportprogress(myList, i);
            //dostuff;
        }

         private void reportprogress<T>(List<T> l, T i)
         {
             progressBar1.Value = ((l.IndexOf(i)) * 100) / l.Count;
             Application.DoEvents();
         }
Luiscencio