dotnet / dotnet/dotnet-api-docs
Is the enumeration order of the Stack<T> collection well defined?
- Dominant language
- C#
- Stars
- 949
- Forks
- 1.7k
- Avg merge
- 3d 27m
- Merged PRs (30d)
- 49
Description
Hi! I used the [`Stack`](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1) collection recently to implement an algorithm, whose correctness now depends on the `Stack` having a LIFO enumeration order. I checked the documentation to see if this enumeration order is well defined, but I can't find an explicit statement about this. I found though an [old StackOverflow question](https://stackoverflow.com/questions/37725449/stack-and-queue-enumeration-order "Stack and Queue enumeration order"), where [the accepted answer](https://stackoverflow.com/a/37725773/11178549) (by Matthew Watson) includes this excerpt:
> **The Stack.GetEnumerator() *strongly implies* that LIFO order is used.**
>
> If you look at [the example for `Stack.GetEnumerator()` in Microsoft's documentation](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1.getenumerator) and inspect the stated output, you can see that it is in LIFO order.
>
> This strongly suggests that Microsoft fully intend a Stack to be enumerated in LIFO order - but they forgot (or didn't bother to) to explicitly document this!
I would like to ask if the current LIFO behavior is just an implementation detail, or if it's a publicly documented guarantee on which algorithms can rely on.
Thanks!
Contributor guide
Assessment
This issue has not been assessed yet.