Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to "see" into the iterating collection of a C# foreach loop while debugging?

This is something I've often wanted to be able to do while debugging. If I have a line of code which computes a collection inside the header of a foreach loop:

foreach ( var item in someObject.GetItems( someParameter ) ) {
    ...
}

There doesn't seem to be anything I can hover over to get the computed set of items returned by GetItems, even though it was clearly computed and returned in order for the loop to be able to execute.

Just seems like something that would be obviously handy. Am I missing something? It's a pain to have to rewrite the code to store the list in a variable just so I can see it while debugging, especially if I discover a bug that isn't easily reproducible.

like image 744
devios1 Avatar asked Apr 05 '11 15:04

devios1


People also ask

Can you iterate through a collection?

An iterator can be used to step through collections such as lists and arrays. An iterator method or get accessor performs a custom iteration over a collection. An iterator method uses the yield return statement to return each element one at a time.

Is there a way to access an iteration counter in Java for each loop?

Adding a Counter to forEach with Stream Let's try to convert that into an operation that includes the counter. This function returns a new lambda. That lambda uses the AtomicInteger object to keep track of the counter during iteration. The getAndIncrement function is called every time there's a new item.

Can I iterate through a list?

Iterating over a list can also be achieved using a while loop. The block of code inside the loop executes until the condition is true. A loop variable can be used as an index to access each element.


2 Answers

One option is to assign it to a temporary variable prior to your loop.

var items = someObject.GetItems( someParameter );
foreach ( var item in items ) {
    ...
}

This will allow you to inspect items directly.

even though it was clearly computed and returned in order for the loop to be able to execute.

The problem is that this is not true.

If GetItems is an IEnumerable or IEnumerable<T>, it may not be evaluated. The "collection" could, in fact, be an infinite enumerable.

like image 196
Reed Copsey Avatar answered Sep 27 '22 20:09

Reed Copsey


One way is to just add the following expression to the watch window

someObject.GetItems(someParameter);

Hovering won't work for this scenario but explicitly adding it to the watch window will. There is a lot of care taking in the code which evaluates expressions during hovering to not evaluate functions. The logic being that functions are expensive, can deadlock the IDE and we don't want a hover operation to cause a deadlock. The GetItems portion of this expression is a function evaluation and hence the EE refuses to evaluate it.

like image 39
JaredPar Avatar answered Sep 27 '22 22:09

JaredPar