views:

583

answers:

3

When iterating through an array using foreach, are there any guaranties that the order in which the elements are returned is the order array[0], array[1], array[2], ...

I know this is how the Array class is implemented now but are there any guaranties for future versions of the framework? The same questions goes for List<>.

A: 

There are no guarantees. Most list/array implementations will return values in order, but there are definitely exceptions, particularly in some of the less common collection classes. (For example, in C5, many collections return values in very different orders than they were added when enumerated.)

Reed Copsey
I disagree with the downvotes here. As I mentioned, there ARE list implementations that do not guarantee order. The standard array in C# as well as the BCL's List<T> classes do guarantee order, but the original question did not limit to just these...
Reed Copsey
A: 

No guarantee by design. foreach is intended for no-order enumeration and implies that the runtime might even process several elements in parallel. You should never rely on any order of enumeration.

sharptooth
+5  A: 

I'd have to disagree with all the answers so far.

First, the C# 3.0 standard guarantees the order of foreach on an array:

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.

-- C# Language Specification Version 3.0, page 240.

Second, on objects, foreach (C#) and For Each (VB.NET) work by using the MoveNext, Reset, and Current members on an object (source). These are typically part of the IEnumerator interface.

In collections that have an order (read: things that implement IList or IList(T)), this means that the elements will be returned in the order that the backing store stores them.

R. Bemrose
+1 as this is correct for all standard arrays and Lists. Though to be pedantic, a custom class that implements IList(T) can implement its own enumerator to return elements in any order it likes.
Joe
Excellent! Thanks. I just won a bet against a collegue :)
Jakob Christensen
This is true for Array, but not necessarily for other collections.
Reed Copsey