louthy/language-ext · error · IndexOutOfRangeException

IndexOutOfRangeException

Error message

IndexOutOfRangeException

What it means

This IndexOutOfRangeException is a bounds guard in the Lst<A> indexer: it throws whenever the caller indexes outside the valid range [0, Root.Count). The faulting input is the index argument passed to the indexer; it indicates off-by-one logic or an assumption the list is longer than it is.

Solutions

  1. Validate: `if (i >= 0 && i < lst.Count)` before indexing.
  2. Prefer foreach/Fold/Map iteration over index-based access.
  3. In generic code, guard the index or clamp it with Math.Clamp/Math.Min before access.

Example fix

// before
var x = lst[i];
// after
if (i < 0 || i >= lst.Count) throw new ArgumentOutOfRangeException(nameof(i));
var x = lst[i];
Defensive patterns

Strategy: validation

Validate before calling

if (index < 0 || index >= lst.Count) throw new ArgumentOutOfRangeException(nameof(index));
var x = lst[index];

Type guard

static Option<A> TryGet<A>(Lst<A> lst, int i) => (uint)i < (uint)lst.Count ? Prelude.Some(lst[i]) : Prelude.None;

Try / catch

try { x = lst[index]; }
catch (IndexOutOfRangeException) { x = default; /* or rethrow as domain error */ }

Prevention

When it happens

Trigger: `lst[i]` with i == lst.Count or i < 0; indexing after removals using a stale index; iterating with `for (i...) lst[i]` where the bound uses a different (larger) collection's count.

Common situations: Off-by-one loop conditions (`<=` instead of `<`); holding an index across a mutation; parsing loops that increment past the end.

Related errors


AI-assisted analysis of louthy/language-ext@2f0e362824 (2026-09-15). Data as JSON: /api/errors/09b68479491ca7f2. Report an issue: GitHub.

Appendix: source

Thrown at LanguageExt.Core/Immutable Collections/List/Internal/Lst.Internal.cs:94

        this.root = root;
    }

    internal ListItem<A> Root
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        get => root;
    }

    /// <summary>
    /// Index accessor
    /// </summary>
    [Pure]
    public A this[int index]
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        get
        {
            if (index < 0 || index >= Root.Count) throw new IndexOutOfRangeException();
            return ListModule.GetItem(Root, index);
        }
    }

    /// <summary>
    /// Number of items in the list
    /// </summary>
    [Pure]
    public int Count
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        get => Root.Count;
    }

    [Pure]
    int IReadOnlyCollection<A>.Count
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]

View on GitHub (pinned to 2f0e362824)