Logically, one would think that the foreach loop in C# would evaluate in the same order as an incrementing for loop. Experimentally, it does. However, there appears to be no such confirmation on the MSDN site.
Is it simply such an apparent answer that they did not think to include that information on the site? Or is there the possibility that it will behave erratically?
There is no foreach in C. You can use a for loop to loop through the data but the length needs to be know or the data needs to be terminated by a know value (eg. null).
You cannot make an infinite foreach loop. foreach is specifically for iterating through a collection. If that's not what you want, you should not be using foreach .
The foreach loop in C# iterates items in a collection, like an array or a list. It proves useful for traversing through each element in the collection and displaying them. The foreach loop is an easier and more readable alternative to for loop.
For arrays (note that System.Array
implements IEnumerable
), it will access elements in order. For other types (IEnumerable
, or having GetEnumerator
), it accesses elements in the order provided, through alternating MoveNext
and Current
calls.
The standard states (ECMA-334 §13.9.5):
"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."
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