Queue<T> / Stack<T>
A first-in, first-out (FIFO) collection Queue<T> and a last-in, first-out (LIFO) collection Stack<T>.
Syntax
// Creates a queue (first-in, first-out). Queue<T> queue = new Queue<T>(); // Creates a stack (last-in, first-out). Stack<T> stack = new Stack<T>();
Method List
| Method | Queue / Stack | Description |
|---|---|---|
| Enqueue(item) | Queue | Adds an element to the end of the queue. |
| Dequeue() | Queue | Removes and returns the element at the front. Throws an exception if the queue is empty. |
| Peek() | Queue / Stack | Returns the element at the front (or top) without removing it. |
| Push(item) | Stack | Pushes an element onto the top of the stack. |
| Pop() | Stack | Removes and returns the element at the top. Throws an exception if the stack is empty. |
| TryDequeue(out T) | Queue | Tries to remove and return an element; returns false if the queue is empty (no exception). |
| TryPop(out T) | Stack | Tries to remove and return an element; returns false if the stack is empty (no exception). |
| Count | Queue / Stack | Returns the number of elements. |
Sample Code
using System;
using System.Collections.Generic;
// Queue (first-in, first-out) example.
Queue<string> waitingList = new Queue<string>();
waitingList.Enqueue("Alice");
waitingList.Enqueue("Bob");
waitingList.Enqueue("Carol");
Console.WriteLine($"Front: {waitingList.Peek()}"); // Alice (not removed)
while (waitingList.Count > 0) {
string next = waitingList.Dequeue();
Console.WriteLine($"Processing: {next}");
}
// Stack (last-in, first-out) example.
Stack<string> history = new Stack<string>();
history.Push("Type text");
history.Push("Change text color");
history.Push("Change font");
// Simulating an "Undo" feature.
Console.WriteLine("Undo:");
while (history.Count > 0) {
Console.WriteLine($" Undo: {history.Pop()}");
}
// Safely retrieve elements using TryDequeue / TryPop.
Queue<int> tasks = new Queue<int>();
if (tasks.TryDequeue(out int value)) {
Console.WriteLine($"Got: {value}");
} else {
Console.WriteLine("The queue is empty.");
}
Overview
Queue<T> is suited for scenarios where items are processed in the order they arrive, such as customer queues, print jobs, and message queues. Stack<T> is used when you need to process the most recent operation first, such as editor undo (Undo) functionality, browser back navigation, and expression parsing.
Calling Dequeue() or Pop() on an empty collection throws an exception. Use TryDequeue() or TryPop() for safe retrieval.
For a collection without duplicates, see HashSet<T>.
If you find any errors or copyright issues, please contact us.