Does HashSet preserve insertion order?

Brian Rasmussen picture Brian Rasmussen · Mar 18, 2009 · Viewed 37.1k times · Source

Does the HashSet collection introduced in .NET 3.5 preserve insertion order when iterated using foreach?

The documentation states, that the collection is not sorted, but it doesn't say anything about insertion order. A pre-release BCL blog entry states that it is unordered, but this article states that it is designed to preserve insertion order. My limited testing suggests, that order is preserved, but that could be a coincidence.

Answer

Michael Burr picture Michael Burr · Mar 18, 2009

This HashSet MSDN page specifically says:

A set is a collection that contains no duplicate elements, and whose elements are in no particular order.