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:

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

Tradeoffs

Questions

Queue 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 needs concurrent access.
  • Queue implementation in dotnet runtime — source code showing the circular buffer and resize logic.

  • Whats next

    Parent
    02 Computer Science

    Pages