TheAlgorithms/C-Sharp · error · InvalidOperationException
The queue contains no items.
Error message
The queue contains no items.
What it means
StackBasedQueue<T>.Dequeue throws InvalidOperationException when both internal input and output stacks are empty, meaning no elements have been enqueued (or all have been dequeued). The two-stack implementation defers transfer, so only the combined emptiness matters.
Solutions
- Check Count > 0 before calling Dequeue.
- Use a while (queue.Count > 0) drain loop instead of a for loop with a fixed count.
- Catch InvalidOperationException when empty dequeue is an expected condition.
- Verify enqueue logic runs before dequeue in producer/consumer flows.
Example fix
// before
while (hasWork) { var item = queue.Dequeue(); } // throws when drained
// after
while (queue.Count > 0) { var item = queue.Dequeue(); } Defensive patterns
Strategy: validation
Validate before calling
if (queue.Count == 0) return; var item = queue.Dequeue();
Try / catch
try
{
var item = queue.Dequeue();
}
catch (InvalidOperationException)
{
// both stacks empty — nothing to dequeue
} Prevention
- Guard with Count > 0 before Dequeue.
- Use while (queue.Count > 0) for drain loops.
- Ensure enqueues precede dequeues in producer/consumer flows.
- Add unit tests covering dequeue-from-empty behavior.
When it happens
Trigger: Calling Dequeue when input.Count == 0 && output.Count == 0 — on a fresh queue or a fully drained one.
Common situations: Consumer loops that dequeue a fixed number of times regardless of enqueue count, drained queue reuse, or a producer that enqueued nothing before consumption.
Understand the failure class
Background: EmptyResultError / "no results found": when an API or scraper succeeds but returns zero rows — this error's family across 9 libraries.
Related errors
- There are no items in the queue.
- Tree is empty!
- Deque is empty.
- There are no items in the queue.
- The queue has reached its capacity.
AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13).
Data as JSON: /api/errors/e423979d07a39b11.
Report an issue: GitHub.
Appendix: source
Thrown at DataStructures/Queue/StackBasedQueue.cs:41
/// <summary>
/// Clears the queue.
/// </summary>
public void Clear()
{
input.Clear();
output.Clear();
}
/// <summary>
/// Returns the first item in the queue and removes it from the queue.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the queue is empty.</exception>
public T Dequeue()
{
if (input.Count == 0 && output.Count == 0)
{
throw new InvalidOperationException("The queue contains no items.");
}
if (output.Count == 0)
{
while (input.Count > 0)
{
var item = input.Pop();
output.Push(item);
}
}
return output.Pop();
}
/// <summary>
/// Returns a boolean indicating whether the queue is empty.
/// </summary>
public bool IsEmpty() => input.Count == 0 && output.Count == 0;View on GitHub (pinned to 96e2905cab)