dotnet/reactive · error · ArgumentOutOfRangeException

index

Error message

index

What it means

ElementAt throws ArgumentOutOfRangeException because the index parameter is negative. The guard at Observable.Aggregates.cs:739 rejects index < 0 synchronously, mirroring LINQ-to-Objects ElementAt semantics. Element positions are zero-based, so 0 is the first element and negative values have no meaning.

Solutions

  1. Clamp or validate the index before the call (Math.Max(0, index)).
  2. If index came from a search operation, check for -1 (not found) before using it.
  3. Use ElementAtOrDefault if you want a default value instead of an exception for out-of-range positions — but still guard negatives since it also throws for index < 0.
  4. Fix the index arithmetic that produced the negative value.

Example fix

// before
var idx = list.IndexOf(item);
var value = await source.ElementAt(idx); // idx == -1 when not found
// after
var idx = list.IndexOf(item);
var value = idx >= 0 ? await source.ElementAt(idx) : defaultValue;
Defensive patterns

Strategy: validation

Validate before calling

if (index < 0) throw new InvalidOperationException("ElementAt index must be non-negative");

Type guard

bool IsValidIndex(int index) => index >= 0;

Try / catch

try { var item = await source.ElementAt(index); }
catch (ArgumentOutOfRangeException ex) when (ex.ParamName == "index") { /* handle negative index */ }

Prevention

When it happens

Trigger: Calling source.ElementAt(index) with index < 0 — e.g. passing -1 as a 'not found' sentinel, computing the index via subtraction (lastIndex - removed) that underflows, or copying an index from a list search that returned -1.

Common situations: Using IndexOf/List.Find results (-1) directly as an ElementAt index; index arithmetic on empty collections where lastIndex becomes -1; off-by-one bugs when translating 1-based user input to 0-based indices.

Understand the failure class

Background: "value must be between 0 and 1" / "out of range" / "must not be negative" errors: fixing range-validation failures across open-source libraries — this error's family across 42 libraries.

Related errors


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

Appendix: source

Thrown at Rx.NET/Source/src/System.Reactive/Linq/Observable.Aggregates.cs:739

        /// Returns the element at a specified index in a sequence.
        /// </summary>
        /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
        /// <param name="source">Observable sequence to return the element from.</param>
        /// <param name="index">The zero-based index of the element to retrieve.</param>
        /// <returns>An observable sequence that produces the element at the specified position in the source sequence.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than zero.</exception>
        /// <exception cref="ArgumentOutOfRangeException">(Asynchronous) <paramref name="index"/> is greater than or equal to the number of elements in the source sequence.</exception>
        public static IObservable<TSource> ElementAt<TSource>(this IObservable<TSource> source, int index)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (index < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(index));
            }

            return s_impl.ElementAt(source, index);
        }

        #endregion

        #region + ElementAtOrDefault +

        /// <summary>
        /// Returns the element at a specified index in a sequence or a default value if the index is out of range.
        /// </summary>
        /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
        /// <param name="source">Observable sequence to return the element from.</param>
        /// <param name="index">The zero-based index of the element to retrieve.</param>
        /// <returns>An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than zero.</exception>

View on GitHub (pinned to 94b5d5ab91)