stack.ToList() – order of elements?
Stack
itself does not have a ToList
method, it's the extension method from the Enumerable
class. As those extension methods only deal with IEnumerable<T>
, it's safe to assume that ToList
iterates over the items of the stack to create the new list (or at least acts exactly as if it would - the Enumerable
methods sometimes test the type of the argument and use an optimized implementation).
Interestingly the documentation does not seem to directly state which order the stack is enumerated in, but the example code does show an order and the examples are part of the documentation. Also, in practice changing the iteration order would break so much code that it would be way too risky to change now.
I also checked with Reflector; Stack<T>
stores its items in an array with the bottommost element at index 0, but its Enumerator
iterates the array in reverse order. Therefore the first element that comes out of the iterator is the top of the stack.
ToList
will iterate in the same order as if you did this:
foreach (T item in stack)
The docs for GetEnumerator()
don't explicitly state the order as far as I can tell, but the example shows that it will iterate as if it were popping. So if you push 1, 2, 3, 4, 5 then ToList
will give you 5, 4, 3, 2, 1.