krahets/hello-algo · error · IndexOutOfRangeException

Index out of bounds

Error message

Index out of bounds

What it means

IndexOutOfRangeException with message "Index out of bounds" is thrown by MyList.Get(int index) when index is negative or >= arrSize (the current element count, not capacity). This is a manual bounds guard wrapping raw array access at arr[index].

Source

Thrown at en/codes/csharp/chapter_array_and_linkedlist/my_list.cs:35

    public MyList() {
        arr = new int[arrCapacity];
    }

    /* Get list length (current number of elements) */
    public int Size() {
        return arrSize;
    }

    /* Get list capacity */
    public int Capacity() {
        return arrCapacity;
    }

    /* Update element */
    public int Get(int index) {
        // If the index is out of bounds, throw an exception, as below
        if (index < 0 || index >= arrSize)
            throw new IndexOutOfRangeException("Index out of bounds");
        return arr[index];
    }

    /* Add elements at the end */
    public void Set(int index, int num) {
        if (index < 0 || index >= arrSize)
            throw new IndexOutOfRangeException("Index out of bounds");
        arr[index] = num;
    }

    /* Direct traversal of list elements */
    public void Add(int num) {
        // When the number of elements exceeds capacity, trigger the extension mechanism
        if (arrSize == arrCapacity)
            ExtendCapacity();
        arr[arrSize] = num;
        // Update the number of elements
        arrSize++;

View on GitHub (pinned to 69932aed18)

Solutions

  1. Validate 0 <= index < list.Size() before calling Get().
  2. Fix off-by-one loop bounds: use i < list.Size(), never i <= list.Size().
  3. For external input, clamp the index to [0, list.Size()-1] or reject out-of-range values explicitly.

Example fix

// before
MyList list = new();
list.Add(10);
int val = list.Get(1); // throws — Size() is 1, valid range [0,0]

// after
if (index >= 0 && index < list.Size()) {
    int val = list.Get(index);
}
Defensive patterns

Strategy: validation

Validate before calling

if (index >= 0 && index < list.Size()) {
    int val = list.Get(index);
}

Try / catch

try {
    int val = list.Get(index);
} catch (IndexOutOfRangeException) {
    // index out of bounds — handle
}

Prevention

When it happens

Trigger: Calling Get(index) where index < 0 or index >= list.Size(). For a freshly constructed MyList, arrSize is 0, so Get(0) already throws.

Common situations: Iterating with an off-by-one loop bound (e.g., <= instead of <), reading an index computed from external input without clamping, or accessing a list before any Add() calls.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/ca9d78ababc51ed7. Report an issue: GitHub.