dotnet/reactive · error · ArgumentOutOfRangeException

index

Error message

index

What it means

Observable.ElementAt's observer tracks whether the requested index was seen; if the source completes before emitting index+1 elements, OnCompleted throws ArgumentOutOfRangeException("index") and forwards it via OnError, since the requested position does not exist.

Solutions

  1. Use ElementAtOrDefault which emits default(T) instead of erroring when the index is out of range
  2. Validate the known length of the sequence before requesting an index
  3. Catch ArgumentOutOfRangeException in OnError and provide a fallback

Example fix

// before
source.ElementAt(5).Subscribe(x => ..., ex => throw ex);
// after
source.ElementAtOrDefault(5).Subscribe(x => Console.WriteLine(x));
Defensive patterns

Strategy: try-catch

Validate before calling

if (index < 0) throw new ArgumentOutOfRangeException(nameof(index));
// only use ElementAt when the sequence is known to have index+1 elements

Try / catch

source.ElementAt(i).Subscribe(
    x => Console.WriteLine(x),
    ex => { if (ex is ArgumentOutOfRangeException) Console.WriteLine(default); else throw ex; });

Prevention

When it happens

Trigger: Calling Observable.ElementAt(source, i) where the source emits fewer than i+1 elements before completing; also negative indices hit the same path.

Common situations: Indexing into a stream based on user input without knowing sequence length; requesting element 5 from a stream that yields only 2 values.

Related errors


AI-assisted analysis of dotnet/reactive@94b5d5ab91 (2026-09-15). Data as JSON: /api/errors/e23509e96f687568. Report an issue: GitHub.

Appendix: source

Thrown at Rx.NET/Source/src/System.Reactive/Linq/Observable/ElementAt.cs:49

            public override void OnNext(TSource value)
            {
                if (_i == 0)
                {
                    ForwardOnNext(value);
                    ForwardOnCompleted();
                }

                _i--;
            }

            public override void OnCompleted()
            {
                if (_i >= 0)
                {
                    try
                    {
                        throw new ArgumentOutOfRangeException("index");
                    }
                    catch (Exception e)
                    {
                        ForwardOnError(e);
                    }
                }
            }
        }
    }
}

View on GitHub (pinned to 94b5d5ab91)