The Stack collection type is similar to other .NET collection types. It has it’s own use cases and is ideally suited to specific scenarios. In this post, I will demonstrate how to use the Stack collection type and go through some of the potential use cases.
What is the Stack Collection Type?
The Stack is a specialized collection that makes use of the three P’s: Peek, Push, and Pop. You may remember that the Queue collection type makes use of a first-in-first-out (FIFO) mechanism. The first item you add to the queue is the first item that can be removed. The Stack is completely opposite. The Stack uses a last-in-first-out (LIFO) mechanism. The last item you added to the stack is the first item that can be removed.
Manipulating Stacks
Manipulating a Stack is done, as already mentioned, by the three P’s.
Peek – Peek allows you to glance at the item at the top of the stack without removing it.
Push – Adds a new item to the Stack.
Pop – Removes and returns the top item on the Stack.
Listing 1.1 – The Three P’s
Stack<string> stringStack = new Stack<string>(); stringStack.Push("test-item-1"); stringStack.Push("test-item-2"); stringStack.Push("test-item-3"); Console.WriteLine(stringStack.Peek()); while (stringStack.Count() > 0) { Console.WriteLine(stringStack.Pop()); } Console.ReadLine();
First, I push three items into the stack. Then, do a peek to show that the item is not removed. Finally, loop through the stack and remove the items. This demonstrates all three P’s.
Listing 1.2 – Output from Listing 1.1
test-item-3 test-item-3 test-item-2 test-item-1
Conclusion
The Stack collection is very similar to the Queue collection. They each have a valid use case and the use cases generally revolve around the way items in the collection are consumed. First-in-first-out or last-in-first-out. Depending on your needs, selecting the correct collection type is as simple as knowing those two rules.