TheAlgorithms/C-Sharp · error · InvalidOperationException

There are no items in the queue.

Error message

There are no items in the queue.

What it means

ArrayBasedQueue.Dequeue throws InvalidOperationException('There are no items in the queue.') when IsEmpty() is true. Dequeuing from an empty queue is an invalid state operation; the error is thrown before any index math runs.

Solutions

  1. Check IsEmpty() (or Count) before each Dequeue.
  2. Catch InvalidOperationException around Dequeue when drain-to-empty is normal.
  3. Fix producer logic so enqueue happens before consumer dequeue attempts.

Example fix

// before
var item = queue.Dequeue(); // throws when empty
// after
if (!queue.IsEmpty())
    var item = queue.Dequeue();
Defensive patterns

Strategy: validation

Validate before calling

if (!queue.IsEmpty())
    var item = queue.Dequeue();

Try / catch

try { var item = queue.Dequeue(); }
catch (InvalidOperationException) { /* queue empty */ }

Prevention

When it happens

Trigger: Calling Dequeue() on a fresh queue or after all items were dequeued, e.g. consumer loops that dequeue more times than producers enqueued.

Common situations: BFS/producer-consumer code where the queue drains faster than expected, or missing the enqueue step on an early-exit path.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/a379c0a832e72d81. Report an issue: GitHub.

Appendix: source

Thrown at DataStructures/Queue/ArrayBasedQueue.cs:43

    ///     Clears the queue.
    /// </summary>
    public void Clear()
    {
        startIndex = 0;
        endIndex = 0;
        isEmpty = true;
        isFull = false;
    }

    /// <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 (IsEmpty())
        {
            throw new InvalidOperationException("There are no items in the queue.");
        }

        var dequeueIndex = endIndex;
        endIndex++;
        if (endIndex >= queue.Length)
        {
            endIndex = 0;
        }

        isFull = false;
        isEmpty = startIndex == endIndex;

        return queue[dequeueIndex];
    }

    /// <summary>
    ///     Returns a boolean indicating whether the queue is empty.
    /// </summary>

View on GitHub (pinned to 96e2905cab)