Advertisement
Intermediate C#, Collections

How does Queue<T> differ from Stack<T> in terms of the order items are removed?

Short answer

Queue is First-In-First-Out (FIFO) — items are removed (Dequeue) in the same order they were added (Enqueue); Stack is Last-In-First-Out (LIFO) — the most recently added item (Push) is the first one removed (Pop).

Save C# mock interview
Advertisement
AModel answer
Queue<T> is First-In-First-Out (FIFO) — items are removed (Dequeue) in the same order they were added (Enqueue); Stack<T> is Last-In-First-Out (LIFO) — the most recently added item (Push) is the first one removed (Pop).
Queue<string> queue = new();
queue.Enqueue("first"); queue.Enqueue("second");
Console.WriteLine(queue.Dequeue()); // 'first'

Stack<string> stack = new();
stack.Push("first"); stack.Push("second");
Console.WriteLine(stack.Pop()); // 'second'
Real-world example
Using Queue<T> for a print job or task processing queue; Stack<T> for an undo/redo history or a depth-first traversal.
Likely follow-ups
  • Which of these two collections would you use to implement a breadth-first graph traversal?
Related topics