Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the foreach loop in C# guarantee an order of evaluation?

Tags:

c#

foreach

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?

like image 842
badpanda Avatar asked Jun 22 '10 23:06

badpanda


People also ask

Is there a foreach loop in C?

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

Is foreach loop infinite?

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 .

What is the purpose of foreach loop?

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.


1 Answers

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

like image 50
Matthew Flaschen Avatar answered Sep 26 '22 03:09

Matthew Flaschen