C# Interview Question #40

What are Stack<T> and Queue<T> in C#?

Generics & Collections Mid-Level Intermediate

Quick Interview Answer

Stack<T> and Queue<T> are generic collections designed for different processing orders.

Detailed Explanation

Stack<T> and Queue<T> are generic collections designed for different processing orders.

Stack<T> follows LIFO: Last In, First Out. The most recently pushed item is removed first. Common operations include Push, Pop, and Peek.

Queue<T> follows FIFO: First In, First Out. The earliest enqueued item is removed first. Common operations include Enqueue, Dequeue, and Peek.

A stack is useful for undo operations, traversal, and nested processing. A queue is useful for work items, message processing, and tasks that should be handled in arrival order.

Code Example

Stack<string> stack = new();
stack.Push("First");
stack.Push("Second");
Console.WriteLine(stack.Pop()); // Second

Queue<string> queue = new();
queue.Enqueue("First");
queue.Enqueue("Second");
Console.WriteLine(queue.Dequeue()); // First