Guaranteed order in a foreach loop
I was always under the impression that the order items are returned via a foreach loop is not guaranteed. For the most part, that is correct. However, it’s not 100%.
I was working on some code today and there was a regular for loop that Resharper offered to convert to a foreach loop. The for loop was moving through an array one item at a time (starting at zero). Since I (incorrectly) assumed the order for a foreach loop was not guaranteed, I was surprised by Resharper’s suggestion.
So I decided to check the C# spec and see what it had to say. Sure enough, I was wrong! Check out section 8.8.4 on the foreach statement. There’s this following tidbit:
The order in which foreach traverses the elements of an array is as follows: For single-dimensional arrays, elements are traversed in increasing index order, starting with index 0 and ending with index Length – 1. For multi-dimensional arrays, elements are traversed such that the indices of the rightmost dimension are increased first, then the next left dimension, and so on to the left.
So Resharper was right. I changed the code and its much cleaner and easier to read!