title: C# foreach loop - is order *stability* guaranteed?
body: <p>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?</p>
  
  <p>Alternatively, given a <code>HashSet&lt;string&gt;</code> with a number of elements, what can cause the output from the the commented lines in the following to be unequal:</p>
  
  <pre><code>{
      var mySet = new HashSet&lt;string&gt;();
      // Some code which populates the HashSet&lt;string&gt;
  
      // Output1
      printContents(mySet);
  
      // Output2
      printContents(mySet);
  }
  
  public void printContents(HashSet&lt;string&gt; set) {
      foreach(var element in set) {
           Console.WriteLine(element);
      }
  }
  </code></pre>
  
  <p>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 <code>Dictionary</code>, <code>List</code> and arrays.</p>