Queue<T> · C#
Dequeue
Removes and returns the element at the front.
public T Dequeue()
Complexity
| Best case | O(1) |
|---|---|
| Worst case | O(1) |
| Extra space | O(1) |
Read at the head index, clear it, advance the head modulo the capacity. Nothing shifts, which is why this beats List<T>.RemoveAt(0).
Tested example
var queue = new Queue<int>([1, 2, 3]);
Assert.Equal(1, queue.Dequeue()); // first in, first out
Assert.Equal(2, queue.Dequeue());
queue.Dequeue();
Assert.Throws<InvalidOperationException>(() => queue.Dequeue()); // empty
Behaviour
- Returns
- The oldest element.
- Errors and preconditions
- InvalidOperationException if the queue is empty.
- Changes
- Count decreases by 1; the slot is cleared for the GC; the head advances.
- Memory and invalidation
- No allocation.