skip to content

In C#, how do Queue<T> and Stack<T> differ in removal and enumeration order, and what happens when you Dequeue or Pop an empty one?

level: juniorimportance: must knowfreq 62%

answer

  1. two ends versus one end
  2. foreach follows removal order
  3. empty means an exception
  4. Try methods return false

basics

~10 s

Queue<T> is first-in-first-out (Enqueue, Dequeue) and Stack<T> is last-in-first-out (Push, Pop); foreach walks each in that removal order. Dequeue, Pop and Peek on an empty one throw InvalidOperationException; TryDequeue, TryPop and TryPeek return false.

solid answer

~40 s

`Queue<T>` hands items back in the order they arrived: `Enqueue` adds at the tail, `Dequeue` takes the head. `Stack<T>` hands back the newest first: `Push` adds on top, `Pop` takes the top. Both have `Peek` to read without removing, and both enumerate in removal order, so `foreach` over a stack starts at the top. Neither has an indexer. On an empty collection, `Dequeue`, `Pop` and `Peek` throw `InvalidOperationException` rather than returning `default`, since `default` could be a real item; `TryDequeue`, `TryPop` and `TryPeek` return `false` instead, which makes a drain loop like `while (queue.TryDequeue(out var job))` clean. One surprise: `new Stack<T>(otherStack)` reverses the order, because the constructor pushes items in enumeration order.

code

csharp · 21 lines
csharp
var waitingForPaper = new Queue<string>();
waitingForPaper.Enqueue("flyers");
waitingForPaper.Enqueue("posters");
waitingForPaper.Enqueue("cards");

var undo = new Stack<string>();
undo.Push("crop");
undo.Push("rotate");
undo.Push("recolor");

Console.WriteLine(string.Join(", ", waitingForPaper));
Console.WriteLine(string.Join(", ", undo));
Console.WriteLine(waitingForPaper.Dequeue() + " / " + undo.Pop());

var copy = new Stack<string>(undo);
Console.WriteLine("copy pops first: " + copy.Peek());

var empty = new Stack<string>();
Console.WriteLine(empty.TryPop(out var last) ? last : "nothing to undo");
try { empty.Pop(); }
catch (InvalidOperationException ex) { Console.WriteLine($"{ex.GetType().Name}: {ex.Message}"); }

go deeper

for a junior

Know which end each type removes from, the three verbs of each (Enqueue, Dequeue, Peek; Push, Pop, Peek), and that an empty Dequeue or Pop throws InvalidOperationException.

for a middle

Explain that both types enumerate in removal order, why they throw rather than return default, and reach for TryDequeue or TryPop in drain loops.

for a senior

Spot the reversed copy from new Stack<T>(stack) in review, and flag a Queue<T> shared between threads without a lock as a correctness bug, not a style point.

for a principal

Treat these as ends-only types: when a design needs removal from the middle or cross-thread hand-off, steer the team to a structure built for that instead of patching around Queue<T>.

## Two orders over the same idea .NET ships two everyday "take from one end" collections in `System.Collections.Generic`: - **`Queue<T>`** is **first-in, first-out (FIFO)**. `Enqueue(T)` adds at the tail, `Dequeue()` removes from the head, and `Peek()` reads the head without removing it. - **`Stack<T>`** is **last-in, first-out (LIFO)**. `Push(T)` adds on top, `Pop()` removes the top, and `Peek()` reads the top without removing it. Neither type gives positional access. There is no indexer: `queue[0]` does not compile and the SDK reports **CS0021** ("Cannot apply indexing with [] to an expression of type 'Queue<int>'"). `Contains(T)` exists, but it is a linear scan using `EqualityComparer<T>.Default`. If you need positions, you wanted a `List<T>`. In a print shop the two fit naturally: jobs waiting for paper go into a `Queue<PrintJob>` because the first job that ran out of paper should be the first to resume, and operator actions go onto a `Stack<EditAction>` because "undo" must reverse the most recent action first. ## What foreach and ToArray show Both types implement `IEnumerable<T>`, so `foreach`, `string.Join` and LINQ work, and they walk the items **in removal order**: | Type | Add / remove | `foreach` order | `ToArray()` order | |---|---|---|---| | `Queue<T>` | `Enqueue` / `Dequeue` | head to tail (oldest first) | the order `Dequeue` would return them | | `Stack<T>` | `Push` / `Pop` | top to bottom (newest first) | the order `Pop` would return them | So after pushing `"crop"`, `"rotate"`, `"recolor"`, `string.Join(", ", undo)` prints `recolor, rotate, crop`. Enumeration does not remove anything, and changing the collection during a `foreach` makes the next `MoveNext` throw `InvalidOperationException` (the enumerator checks a version number). ```csharp var undo = new Stack<string>(); undo.Push("crop"); undo.Push("rotate"); undo.Push("recolor"); var copy = new Stack<string>(undo); // enumerates undo top-first, pushing each item Console.WriteLine(copy.Peek()); // crop - the copy is reversed ``` That last line is the classic surprise: the `Stack<T>(IEnumerable<T>)` constructor pushes items in the order it enumerates them, and a stack enumerates top first, so the copy comes out upside down. `new Stack<string>(undo.Reverse())` keeps the original pop order. ## Empty collections: throw or Try Calling `Dequeue()` or `Peek()` on an empty `Queue<T>`, or `Pop()` or `Peek()` on an empty `Stack<T>`, throws **`InvalidOperationException`** (messages "Queue empty." and "Stack empty." in the reference source). They do not return `null` or `default`, because `default` could be a real value: a `Queue<int>` may legitimately hold `0`. The non-throwing forms follow the Try pattern: 1. `queue.TryDequeue(out T result)` and `stack.TryPop(out T result)` remove and return `true`, or set `result` to `default` and return `false`. 2. `queue.TryPeek(out T result)` and `stack.TryPeek(out T result)` read without removing. 3. A drain loop becomes `while (waiting.TryDequeue(out var job)) Print(job);`, with no `Count` check and no exception used as control flow. Checking `Count > 0` before `Dequeue()` is equally correct in single-threaded code; the Try method simply does the check and the removal in one call. `TryPeek` earns its keep in UI code too. An editor's Undo button can stay disabled while `undo.TryPeek(out var next)` returns `false`, and otherwise show a label such as "Undo recolor" built from `next`, all without removing anything or catching an exception on every repaint. ## Generic versus the old non-generic types `System.Collections` still contains the pre-generics `Queue` and `Stack` classes. They store `object`, so every value type you add is boxed and every read needs a cast; the boxing cost itself is a separate topic. New code uses the generic `Queue<T>` and `Stack<T>`, which keep the same FIFO and LIFO rules, the same `InvalidOperationException` on an empty removal, and add the Try methods. When an interviewer says "queue" or "stack" in modern C#, they mean the generic types. ## Traps worth naming in an interview - **Copying a stack reverses it**, as shown above. - **No indexer and no `Remove(T)`**: these are ends-only types. Removing an arbitrary job from a waiting line needs a different structure. - **Not thread-safe**: concurrent `Enqueue` and `Dequeue` from several threads can corrupt a `Queue<T>`; the thread-safe containers are a separate topic. - **`Peek` versus `Dequeue`**: `Peek` leaves the item in place, so a loop that only peeks never ends. - **Reference types stay reachable only while queued**: `Dequeue` and `Pop` clear the vacated array slot, so the removed object can be collected once your code drops it. Knowing the two orders is the junior bar; knowing that `foreach` follows removal order, that empty removal throws rather than returning `default`, and that the Try methods exist is what makes the answer complete.

  • Why does new Stack<T>(existingStack) come out in the opposite order, and how do you keep the order?
    The `Stack<T>(IEnumerable<T>)` constructor enumerates its source and pushes each item in turn. A stack enumerates from the top, so the old top is pushed first and ends at the bottom of the copy. Passing `existingStack.Reverse()` (LINQ's `Enumerable.Reverse`) feeds the items bottom-first, so the copy pops in the original order.
  • Is checking Count before calling Dequeue any worse than calling TryDequeue?
    In single-threaded code both are correct. `TryDequeue(out T)` does the emptiness check and the removal in one call and reads better in a drain loop. Neither makes `Queue<T>` safe when several threads touch it: with concurrent access the check and the removal can interleave, so that case needs a lock or a thread-safe collection.

  • Dequeue on an empty Queue<T> returns null or default.
  • foreach over a Stack<T> lists items in the order they were pushed.
  • Queue<T> has an indexer, so queue[0] reads the head.
  • Copying a stack with new Stack<T>(old) keeps the same pop order.
  • Catching InvalidOperationException is the normal way to drain a queue.