Superbest Superbest - 4 months ago 57
C# Question

C# foreach loop - is order *stability* guaranteed?

Suppose I have a given collection. Without ever changing the collection in any way, I loop through its contents twice with a foreach. Barring cosmic rays and what not, is it absolutely guaranteed that the order will be consistent in both loops?

Alternatively, given a

with a number of elements, what can cause the output from the the commented lines in the following to be unequal:

var mySet = new HashSet<string>();
// Some code which populates the HashSet<string>

// Output1

// Output2

public void printContents(HashSet<string> set) {
foreach(var element in set) {

It would be helpful if I could get a general answer explaining what causes an implementation to not meet the criteria described above. Specifically, though, I am interested in
and arrays.


Array enumeration guarantees order.

List and List<T> are expected to provide stable order (since they are expected to implement sequentially-indexed elements).

Dictionary, HashSet are explicitly do not guarantee order. Its is very unlikely that 2 calls to iterate items one after each other will return items in different order, but there is no guarantees or expectations. One should not expect any particular order.

Sorted versions of Dictionary/HashSet return items in sort order.

Other IEnumerable objects are free to do whatever they want. Normally one implements iterators in such a way that it matches user's expectations. I.e. enumeration of something that have implicit order should be stable, if explicit order provided - expected to be stable. Query to database that does not specify order should be expected to return items in semi-random order.

Check this question for links: Does the foreach loop in C# guarantee an order of evaluation?