Is it possible to “see” a C # foreach loop in an iterative collection during debugging?

This is what I often wanted to do during debugging. If I have a line of code that computes a collection inside the foreach loop header:

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

There seems to be nothing I can do to get the computed set of elements returned by GetItems , although it was explicitly computed and returned so the loop could run.

It just seems that it would be convenient. Am I missing something? It is a pain to rewrite the code to store the list in a variable so that I can see it during debugging, especially if I find an error that is not easy to reproduce.

+4
source share
3 answers

One way is to simply add the following expression to the viewport

 someObject.GetItems(someParameter); 

Guidance will not work for this scenario, but will explicitly add it to the viewport. There are many worries in the code that evaluate expressions during a hang so as not to evaluate functions. The logic is that the functions of the road can block the IDE, and we do not want the hang operation to cause a dead end. Part of this GetItems expression is an evaluation of a function, and therefore EE refuses to evaluate it.

+3
source

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

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

This will allow you to directly check items .

although it was explicitly computed and returned so the loop could execute.

The problem is that this is not true.

If GetItems is IEnumerable or IEnumerable<T> , it cannot be evaluated. A “collection” could be, in fact, an infinite enumerable.

+9
source

The Visual Studio debugger does not have a function for this, unfortunately.

Please note that in general it cannot. The collection may be an iterator block with complex calculations; you don’t need the debugger to evaluate it more often than the program.

But of course, there is an obvious workaround for storing a collection in a variable:

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

Now you can see the items in the debugger. Of course, the same restrictions apply - if it is a complex enumeration, the debugger will not display a convenient list of elements. But in normal cases (e.g. lists, arrays, etc.) it does.

+1
source

Source: https://habr.com/ru/post/1346771/


All Articles