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