helpME1986 helpME1986 - 2 years ago 111
C# Question

C# Linq different values printed than presented in debug mode

var counter=0;
var array = new int[] {0, 1, 2, 3,4};

var test = array.Select(a => counter++);

foreach (var item in test)


When I run the code above the console prints 0,1,2,3,4.
However, when I expand test array in the debug mode I can see numbers from 10 to 14. Why??
Also, can you help me why the console does not print 1,2,3,4,5 as it should return incremented counter.


Answer Source

The reason the output keeps changing is that test isn't actually evaluated until you enumerate through it. So opening up the debug view causes it to evaluate the enumeration. Then every time you enumerate it, it will run again, each time the counter variable increasing. So you can get some funny results by running the for loop multiple times or printing out test.First() multiple times.

You can prevent this by forcing the enumerable to materialise into a list:

var test = array.Select(a => counter++).ToList();
//                                     ^^^^^^^^^

As for why it starts at zero, that's because ++ in this context is a post-increment operator meaning it returns the value and then increments. If you want it to start at 1, prefix the variable instead:

var test = array.Select(a => ++counter).ToList();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download