These classes (available in System.Collections namespace) are designed to contain primary type collections of objects. Collections of oftects with revelant storing and retrieval order. We will also see the Generic Stack and the Generic Queue (in the System.Collections.Generic namespace).
Stack is based on the LIFO principle (Last-In-First-Out), this means that the elements are added or removed at the same end.
Queue follows the FIFO principle (First-In-First-Out), this is, the first element that gets in is the first that goes out when the elements are removed.
Lets see that on a sample:
Stack:
System.Collections.Stack myStack = new Stack();
myStack.Push(«1»);
myStack.Push(«2»);
myStack.Push(«3»);
myStack.Push(«4»);
myStack.Push(«5»);
Console.WriteLine(«Top element: » + myStack.Peek()); // gives the top object without removing it
Console.WriteLine(«Total elements: » + myStack.Count); //total number of items
while (myStack.Count > 0)
{
Console.Write(» » + myStack.Pop()); // Pop() returns and removes the object from the stack
}
The output whould be:
Top element: 5
Total elements: 5
5 4 3 2 1
Queue:
Queue myQueue = new Queue();
myQueue.Enqueue(«1»);
myQueue.Enqueue(«2»);
myQueue.Enqueue(«3»);
myQueue.Enqueue(«4»);
myQueue.Enqueue(«5»);
Console.WriteLine(«Top element: » + myQueue.Peek()); // gives the top object without removing it
Console.WriteLine(«Total elements: » + myQueue.Count); //total number of items
while (myQueue.Count > 0)
{
Console.Write(» » + myQueue.Dequeue()); // Dequeue() returns and removes the object from the stack
}
Top element: 5
Total elements: 5
1 2 3 4 5
More info:
MSDN – Stack class
MSDN – Queue class
Generic versions of Queue and Stack
¿Why a generic version of these classes? Non generic collections (primary collections) can contain any type of object. In fact, the elements type of a queue or stack is Object. This means that the .Net Framework has to do boxing and unboxing each time we use these classes to store value types, and casts to store reference types.
With generic collections, is needed to declare in a strong way the type of the collection. This fact is the only difference with primary collections. This is demonstrated by the following code:
System.Collections.Generic.Queue<string> myQueue;
myQueue = new System.Collections.Generic.Queue<string>;
myQueue.Enqueue(«1»);
myQueue.Enqueue(«2»);
myQueue.Enqueue(«3»);
myQueue.Enqueue(«4»);
myQueue.Enqueue(«5»);
Console.WriteLine(«Top element: » + myQueue.Peek());
Console.WriteLine(«Total elements: » + myQueue.Count);
while (myQueue.Count > 0)
{
Console.Write(» » + myQueue.Dequeue());
}
So… ¿how do we know wich is the best choice for our code? If you know the type your Queue or Stack will contain, you should use the Generic version of these classes.
great post! 😉