Is this guaranteed to always print 123
?
Queue<string> theQueue = new Queue<string>();
theQueue.Enqueue("1");
theQueue.Enqueue("2");
theQueue.Enqueue("3");
foreach(var str in theQueue)
{
Console.Write(str);
}
Console.WriteLine();
Edit:
I totally agree that a queue that enumerated in any other order would be obviously incorrect. That's why I asked the question. However, the abstract data type queue
only makes guarantees about its enqueue
and dequeue
operations.
I'm looking for an answer that references documentation that guarantees this ordering in the .NET BCL.
Documentation Proof:
Yes it is, from the MSDN Documenation of GetEnumerator, emphisis mine
However that does not address what the first element in the collection will be. To answer that we need to go to the description of Queue itself:
Combining the two above statements we have the official code contract that the first object returned from the Enumerator will be the first element in the collection and the fact that the first element in the collection will be the first-in object added to the collection giving us our final output that iterating over a
Queue<T>
will always be in order.As an aside, compare that to a
Dictionary
, the definition for GetEnumerator() states the same line about retrieving the first element first. However Dictionary's description does include the explicit ordering of objects in the collection:And that is why it is "legal" for a
Dictionary
not to return in insertion order.