TheAlgorithms/C-Sharp · error · InvalidOperationException

Cannot prune empty list

Error message

Cannot prune empty list

What it means

This InvalidOperationException is the empty-list guard at the top of DoublyLinkedList.Remove (DoublyLinkedList.cs:248). Remove unlinks the tail node by moving Tail to Tail.Previous; when Tail is null the list is empty, so there is no last node to prune. It fires when Remove (or RemoveNode's delegated removal path) is invoked on a list with Count == 0.

Solutions

  1. Check Count > 0 before calling Remove.
  2. Catch InvalidOperationException if empty-at-pop-time is an expected condition.
  3. Track add/remove balance so Remove is only called when a prior Add succeeded.

Example fix

// before
list.Remove(); // may throw on empty
// after
if (list.Count > 0) list.Remove();
Defensive patterns

Strategy: validation

Validate before calling

if (list.Count > 0) list.Remove();

Try / catch

try { list.Remove(); }
catch (InvalidOperationException) { /* list was empty */ }

Prevention

When it happens

Trigger: Calling Remove() on an empty list, or calling it more times than elements were added.

Common situations: Undo-style pop loops that pop once per event when some events added nothing, or miscounted insert/remove pairs.

Related errors


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

Appendix: source

Thrown at DataStructures/LinkedList/DoublyLinkedList/DoublyLinkedList.cs:248

        if (Head is null)
        {
            Tail = null;
            Count = 0;
            return;
        }

        Head.Previous = null;
        Count--;
    }

    /// <summary>
    ///     Removes the last node in the list.
    /// </summary>
    public void Remove()
    {
        if (Tail is null)
        {
            throw new InvalidOperationException("Cannot prune empty list");
        }

        Tail = Tail.Previous;
        if (Tail is null)
        {
            Head = null;
            Count = 0;
            return;
        }

        Tail.Next = null;
        Count--;
    }

    /// <summary>
    ///     Removes specific node.
    /// </summary>
    /// <param name="node"> Node to be removed.</param>

View on GitHub (pinned to 96e2905cab)