Queue
Intro
Queue<T> is a FIFO (first in, first out) collection. The earliest enqueued item is processed first. Use it for buffering, breadth-first traversal, and producer-consumer style pipelines.
Queue<T> is implemented as a circular buffer in .NET:
Enqueueadds at the tail;Dequeueremoves from the head.- Head/tail indices wrap around instead of shifting elements.
- Operations are O(1) on average, with occasional O(n) resize copies.
Because head and tail indices advance modulo the array length, neither Enqueue nor Dequeue shifts elements — only index arithmetic occurs. When the buffer fills completely, the queue copies all elements to a larger array with the head reset to index 0, then resumes the circular layout. This one-time O(n) resize is amortized over many operations so steady-state throughput stays O(1).
Structure
graph LR
F[front] --> A[item one] --> B[item two] --> C[item three] --> T[back]Example
var jobs = new Queue<string>();
jobs.Enqueue("job-1");
jobs.Enqueue("job-2");
Console.WriteLine(jobs.Dequeue()); // job-1
Console.WriteLine(jobs.Peek()); // job-2
Pitfalls
Dequeue/Peekon an empty queue throwsInvalidOperationException. Guard withCountwhen queue emptiness is expected.- Using a queue where priority matters can delay urgent work. Switch to
PriorityQueue<TElement, TPriority>when ordering by priority is required. - Unbounded enqueues can grow memory silently in bursty systems. Apply backpressure or capacity policies at architecture boundaries.
Tradeoffs
Queue<T>vsStack<T>: queue preserves arrival order, stack prioritizes newest items.Queue<T>vsChannel<T>: queue is simple in-memory buffering, channels provide richer async coordination for concurrent producers/consumers.
Questions
Queue<T> suitable for BFS?BFS processes nodes in discovery order by levels. FIFO behavior naturally enforces this traversal order.
Queue<T> with PriorityQueue<TElement, TPriority>?When business correctness depends on priority rather than arrival time, such as shortest-path, scheduler, or SLA-driven dispatching.
Complexity is not the only risk. If producers outpace consumers, memory grows and latency spikes. Throughput and backpressure design matter more than method complexity.
Links
Queue<T>class — API reference covering Enqueue, Dequeue, Peek, and circular buffer internals.PriorityQueue<TElement, TPriority>class — use when ordering by priority rather than arrival time is required.- Collections in .NET — overview of all collection types with complexity and usage guidance.
- System.Threading.Channels library — async producer-consumer channels; the right upgrade path when
Queue<T>needs concurrent access. - Queue implementation in dotnet runtime — source code showing the circular buffer and resize logic.
Parent
02 Computer Science
Pages