krahets/hello-algo · error · IndexOutOfRangeException

索引越界

Error message

索引越界

What it means

Thrown by my_list.Get(int index) (zh-hant/codes/csharp/chapter_array_and_linkedlist/my_list.cs:35) as System.IndexOutOfRangeException with message "索引越界" ("index out of range") when index is outside [0, arrSize). This is the correct, specific exception type for a bounds violation in a list-like container. Get reads 'arr[index]', so the guard protects the backing array.

Source

Thrown at zh-hant/codes/csharp/chapter_array_and_linkedlist/my_list.cs:35

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

    /* 獲取串列長度(當前元素數量)*/
    public int Size() {
        return arrSize;
    }

    /* 獲取串列容量 */
    public int Capacity() {
        return arrCapacity;
    }

    /* 訪問元素 */
    public int Get(int index) {
        // 索引如果越界,則丟擲異常,下同
        if (index < 0 || index >= arrSize)
            throw new IndexOutOfRangeException("索引越界");
        return arr[index];
    }

    /* 更新元素 */
    public void Set(int index, int num) {
        if (index < 0 || index >= arrSize)
            throw new IndexOutOfRangeException("索引越界");
        arr[index] = num;
    }

    /* 在尾部新增元素 */
    public void Add(int num) {
        // 元素數量超出容量時,觸發擴容機制
        if (arrSize == arrCapacity)
            ExtendCapacity();
        arr[arrSize] = num;
        // 更新元素數量
        arrSize++;

View on GitHub (pinned to 69932aed18)

Solutions

  1. Validate '0 <= index < list.Size()' before calling Get.
  2. Fix loop bounds to '< list.Size()' rather than '<='.
  3. Use the list's own Size()/Capacity() rather than the backing array length when computing indices.
  4. Add a TryGet(int, out int) helper or clamp the index if out-of-range should not be fatal.

Example fix

// before
int v = list.Get(i);   // i may be == Size()
// after
if (i < 0 || i >= list.Size()) return;
int v = list.Get(i);
Defensive patterns

Strategy: validation

Validate before calling

// Before calling Get on my_list
if (index >= 0 && index < list.Size()) {
    int v = list.Get(index);
}

Try / catch

try { int v = list.Get(index); }
catch (IndexOutOfRangeException) { /* index out of range: clamp or report */ }

Prevention

When it happens

Trigger: Calling Get(index) where index < 0 or index >= arrSize — e.g. Get(arrSize), Get(-1), or Get on an index computed from an off-by-one loop bound.

Common situations: Looping 'for (i=0; i<=arrSize; i++)' (<= instead of <); reading the slot at the logical end (arrSize) instead of arrSize-1; passing an externally computed index without clamping; forgetting that arrCapacity != arrSize.

Related errors


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