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

  1. Check Count > 0 before calling Dequeue.
  2. Use a while (queue.Count > 0) drain loop instead of a for loop with a fixed count.
  3. Catch InvalidOperationException when empty dequeue is an expected condition.
  4. 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

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


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)