When using the .ToList() extension method on a Stack<T>, is the result the same as popping each element and adding to a new list (reverse of what was pushed)?
If so, is this because it really is iterating over each element, or does it store the elements in reverse internally and slip the array into a new List<T>?
Stackitself does not have aToListmethod, it’s the extension method from theEnumerableclass. As those extension methods only deal withIEnumerable<T>, it’s safe to assume thatToListiterates over the items of the stack to create the new list (or at least acts exactly as if it would – theEnumerablemethods 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 itsEnumeratoriterates the array in reverse order. Therefore the first element that comes out of the iterator is the top of the stack.