C# · FIFO queue · container
Queue<T>
A first-in, first-out queue on a circular array: O(1) dequeue and amortized O(1) enqueue.
using System.Collections.Generic; public class Queue<T> : IEnumerable<T>, IReadOnlyCollection<T>
.NET 10 (TryDequeue/TryPeek since .NET Core 2.0)
Operations
| Operation | Time | Worst case | Changes the collection |
|---|---|---|---|
| Enqueue | O(1) | O(n) when the buffer is full | Yes |
| Dequeue | O(1) | O(1) | Yes |
| Peek / TryPeek | O(1) | O(1) | No |
| TryDequeue | O(1) | O(1) | Yes |
"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.
How it works
- Representation
- A T[] used as a ring buffer with head and tail indices that wrap around; it grows (doubling) when full.
- Ordering
- FIFO: elements leave in the order they arrived; enumeration goes front to back.
- Duplicates
- Allowed.
- Mutability
- Mutable; modifying during enumeration throws.
- Memory and ownership
- Capacity ≥ Count; does not shrink automatically (TrimExcess).
- Equality and comparison
- Contains uses EqualityComparer<T>.Default (O(n) scan).
Python (collections.deque), Java (ArrayDeque) and C++ (std::deque) all ship a double-ended queue; .NET does not.
Pitfalls
- Dequeue and Peek on an empty queue throw InvalidOperationException; use TryDequeue/TryPeek.
- .NET has no general double-ended queue in the standard library: Queue<T> only adds at the back and removes at the front. Use LinkedList<T> (O(1) at both ends, poor locality) or write a ring-buffer deque.
- Do not use List<T>.RemoveAt(0) as a queue: it shifts every element.
Alternatives
- Stack<T> for LIFO
- LinkedList<T> as a deque
- PriorityQueue<TElement, TPriority> to serve by priority
- Channel<T> or ConcurrentQueue<T> between threads
In other languages
- Python: collections.deque
- Java: ArrayDeque<E>
- C++: std::deque<T>