dotnet/wpf · error · IndexOutOfRangeException

SR.TextElementCollection_IndexOutOfRange

Error message

SR.TextElementCollection_IndexOutOfRange

What it means

Thrown by TextElementCollection<T>.Insert as an IndexOutOfRangeException when index is negative. The method validates the value type first, then rejects negative indices because a text-tree position cannot precede the start.

Solutions

  1. Clamp the index: Math.Max(0, index) before calling Insert.
  2. Use Add when the collection is empty or you want an append.
  3. Check index >= 0 and <= count before inserting.

Example fix

// before
int i = blocks.IndexOf(existing); // -1 when not found
blocks.Insert(i, newBlock);
// after
int i = blocks.IndexOf(existing);
if (i < 0) blocks.Add(newBlock); else blocks.Insert(i, newBlock);
Defensive patterns

Strategy: validation

Validate before calling

if (index >= 0 && index <= collection.Count)
    collection.Insert(index, value);

Type guard

bool IsValidIndex(int i, int count) => i >= 0 && i <= count;

Try / catch

try { collection.Insert(index, value); }
catch (IndexOutOfRangeException) { collection.Add(value); /* fall back to append */ }

Prevention

When it happens

Trigger: Calling Insert(-1, value) — commonly from code computing an index like (indexOf - 1) on an empty collection, or deserialization supplying a bad index.

Common situations: Index arithmetic on empty collections (IndexOf returns -1); loops decrementing past 0; off-by-one in insertion logic.

Related errors


AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14). Data as JSON: /api/errors/299968d9f7b0c5bc. Report an issue: GitHub.

Appendix: source

Thrown at src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Documents/TextElementCollection.cs:458

        int IList.IndexOf(object value)
        {
            return IndexOfInternal(value, false /* isCacheSafePreviousIndex */);
        }

        void IList.Insert(int index, object value)
        {
            ArgumentNullException.ThrowIfNull(value);

            TextElementType newItem = value as TextElementType;

            if (newItem == null)
            {
                throw new ArgumentException(SR.Format(SR.TextElementCollection_TextElementTypeExpected, typeof(TextElementType).Name), nameof(value));
            }

            if (index < 0)
            {
                throw new IndexOutOfRangeException(SR.TextElementCollection_IndexOutOfRange);
            }

            if (newItem.Parent != null)
            {
                throw new ArgumentException(SR.Format(SR.TextSchema_TheChildElementBelongsToAnotherTreeAlready, this.GetType().Name));
            }

            ValidateChild(newItem);

            this.TextContainer.BeginChange();
            try
            {
                TextPointer position;

                if (this.FirstChild == null)
                {
                    if (index != 0)
                    {

View on GitHub (pinned to 81131a70a4)