Basic Collections - Stacks
(Page 4 of 6 )
Stacks
Stacks are similar to queues in that you can't directly access most of the elements. However, a stack is a last-in-first-out (LIFO) collection. Imagine, for example, a stack of papers. Let's be more specific and say that it's a short stack of two papers. While the bottom paper was the first paper to be put into the stack, it cannot be accessed without first taking off the top piece of paper. This is how a stack, which is represented by the appropriately-named Stack class, operates. The last element to be put into, or pushed onto, a Stack is the first element that may be taken out, or popped from the Stack. Let's create a (generic) Stack of string objects:
Stack<string> genericStack1 = new Stack<string>();
Elements can be pushed onto the stack using the Push method. Here, we push three strings onto the stack:
genericStack1.Push("first");
genericStack1.Push("second");
genericStack1.Push("third");
The last element can be popped off (which will remove the item) using the Pop method:
string lastOn = genericStack1.Pop();
As with a Queue, we can also peek at the last element without removing it by using the Peek method:
string notRemoved = genericStack1.Peek();
We can also loop through the elements of a Stack without disturbing them:
foreach (string element in genericStack1)
{
Console.WriteLine(element);
}
Stack also features a Contains method, a Clear method and a ToArray method which all work just as they do in a Queue:
bool fourthFound = genericStack1.Contains("fourth");
genericStack1.Clear();
string[] willNotContainAnything = genericStack1.ToArray();
Next: Dictionaries >>
More ASP.NET Articles
More By Peyton McCullough