views:

90

answers:

2

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>?

+3  A: 

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, it's safe to assume that ToList 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 its Enumerator iterates the array in reverse order. Therefore the first element that comes out of the iterator is the top of the stack.

Matti Virkkunen
Why is it safe to assume that? I haven't been able to find anything in the documentation that states in which order the Enumerator for `Stack<T>` iterates, but maybe I haven't look well enough...
Mark Seemann
+1  A: 

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.

Jon Skeet