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>
?
Stack
itself does not have aToList
method, it's the extension method from theEnumerable
class. As those extension methods only deal withIEnumerable
, it's safe to assume thatToList
iterates over the items of the stack to create the new list.Updated: I checked with Reflector;
Stack<T>
stores its items in an array with the bottommost element at index 0, but itsEnumerator
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: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 thenToList
will give you 5, 4, 3, 2, 1.