Collections
Stacks
A stack is a collection type that providers a first-in, last our API. The idea behind a stack, is that you can push items onto a stack and pop them off in reverse order.
using System; using System.Collections.G...Like we have seen of other collection types, the stack is also backed by an array. Mechanically though, the array is managed so that items are read in reverse order. Here is a diagram to help make sense of this concept:
To declare a stack, you use the Stack<T> generic type, where T is your element type, so to declare a stack of type string
Stack<string> names = new Stack<string>();
The element type can be anything:
Stack<DateTime> calendar = new Stack<DateTime>(); Stack<int> sequence = new Stack<int>();
You can also substitute var to allow the compiler to infer the type:
var names = new Stack<string>();
Adding items to the stack
The Stack<T> expresses a Push method instead of the usual collection Add method. This will add the item to the last available position in the underlying array:
names.Push("C3PO");
Removing items from the stack
Again, like the previous Push method seen previously, the converse method for removing items is Pop. This will remove the last item that was added to the underlying array:
string name = names.Pop();
If you call Pop and the stack is empty, then an InvalidOperationException will be thrown, so it's best to check the Count property to make sure at least 1 item exists before calling Pop.
If you want to check the next item before removing it, you can call Peek.
Looping through the stack
Like all other collections, you can use a foreach iterator to move through the queue. You can also use a while loop with a check against the Count property.
When you enumerate using foreach, you can read the items from the stack without removing them:
foreach (string name in names) { // The item has not been removed from the stack. Console.WriteLine(name); }
Whereas using the Pop method:
while (names.Count > 0) { // The item has been removed from the stack. Console.WriteLine(names.Pop()); }
There is another type of loop, the 'do-while' loop that operates in a similar fashion to the 'while' loop with one key difference. The condition check in the loop is processed after each run, instead of before each run:
do { Console.WriteLine(names.Pop()); } while (names.Count > 0);
The key difference here is we would need to check to see if the stack contained at least 1 item first before we process the loop.