TheAlgorithms/C-Sharp · error · ArgumentOutOfRangeException

index

Error message

index

What it means

GetElementByIndex throws ArgumentOutOfRangeException with paramName 'index' when a negative index is requested. Negative indices are not supported (no from-the-end semantics) so the call is rejected before traversal.

Solutions

  1. Validate index >= 0 before the call.
  2. Fix loop/counter logic that can produce negative values.
  3. Catch ArgumentOutOfRangeException around the call when input is untrusted.

Example fix

// before
var item = list.GetElementByIndex(userIndex); // could be -1
// after
if (userIndex >= 0 && userIndex < list.Length())
    var item = list.GetElementByIndex(userIndex);
Defensive patterns

Strategy: validation

Validate before calling

if (index >= 0 && index < list.Length())
    var item = list.GetElementByIndex(index);

Type guard

bool IsValidIndex(int i, int length) => i >= 0 && i < length;

Try / catch

try { var item = list.GetElementByIndex(index); }
catch (ArgumentOutOfRangeException) { /* invalid index */ }

Prevention

When it happens

Trigger: Calling GetElementByIndex(-1) or any negative value, typically from uninitialized counter variables or 1-based input not converted.

Common situations: Loop variables that underflow (i starts at 0 and is decremented), user-supplied positions parsed without sign validation.

Related errors


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

Appendix: source

Thrown at DataStructures/LinkedList/SinglyLinkedList/SinglyLinkedList.cs:68

        {
            tempElement = tempElement.Next;
        }

        // adds the new element to the last one
        tempElement.Next = newListElement;
        return newListElement;
    }

    /// <summary>
    ///     Returns element at index <paramref name="index" /> in the list.
    /// </summary>
    /// <param name="index">Index of an element to be returned.</param>
    /// <returns>Element at index <paramref name="index" />.</returns>
    public T GetElementByIndex(int index)
    {
        if (index < 0)
        {
            throw new ArgumentOutOfRangeException(nameof(index));
        }

        var tempElement = Head;

        for (var i = 0; tempElement is not null && i < index; i++)
        {
            tempElement = tempElement.Next;
        }

        if (tempElement is null)
        {
            throw new ArgumentOutOfRangeException(nameof(index));
        }

        return tempElement.Data;
    }

    public int Length()

View on GitHub (pinned to 96e2905cab)