{"record":{"id":"299968d9f7b0c5bc","repo":"dotnet/wpf","slug":"sr-textelementcollection-indexoutofrange","errorCode":null,"errorMessage":"SR.TextElementCollection_IndexOutOfRange","messagePattern":"SR\\.TextElementCollection_IndexOutOfRange","errorType":"exception","errorClass":"IndexOutOfRangeException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Documents/TextElementCollection.cs","lineNumber":458,"sourceCode":"        int IList.IndexOf(object value)\n        {\n            return IndexOfInternal(value, false /* isCacheSafePreviousIndex */);\n        }\n\n        void IList.Insert(int index, object value)\n        {\n            ArgumentNullException.ThrowIfNull(value);\n\n            TextElementType newItem = value as TextElementType;\n\n            if (newItem == null)\n            {\n                throw new ArgumentException(SR.Format(SR.TextElementCollection_TextElementTypeExpected, typeof(TextElementType).Name), nameof(value));\n            }\n\n            if (index < 0)\n            {\n                throw new IndexOutOfRangeException(SR.TextElementCollection_IndexOutOfRange);\n            }\n\n            if (newItem.Parent != null)\n            {\n                throw new ArgumentException(SR.Format(SR.TextSchema_TheChildElementBelongsToAnotherTreeAlready, this.GetType().Name));\n            }\n\n            ValidateChild(newItem);\n\n            this.TextContainer.BeginChange();\n            try\n            {\n                TextPointer position;\n\n                if (this.FirstChild == null)\n                {\n                    if (index != 0)\n                    {","sourceCodeStart":440,"sourceCodeEnd":476,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Documents/TextElementCollection.cs#L440-L476","documentation":"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.","triggerScenarios":"Calling Insert(-1, value) — commonly from code computing an index like (indexOf - 1) on an empty collection, or deserialization supplying a bad index.","commonSituations":"Index arithmetic on empty collections (IndexOf returns -1); loops decrementing past 0; off-by-one in insertion logic.","solutions":["Clamp the index: Math.Max(0, index) before calling Insert.","Use Add when the collection is empty or you want an append.","Check index >= 0 and <= count before inserting."],"exampleFix":"// before\nint i = blocks.IndexOf(existing); // -1 when not found\nblocks.Insert(i, newBlock);\n// after\nint i = blocks.IndexOf(existing);\nif (i < 0) blocks.Add(newBlock); else blocks.Insert(i, newBlock);","handlingStrategy":"validation","validationCode":"if (index >= 0 && index <= collection.Count)\n    collection.Insert(index, value);","typeGuard":"bool IsValidIndex(int i, int count) => i >= 0 && i <= count;","tryCatchPattern":"try { collection.Insert(index, value); }\ncatch (IndexOutOfRangeException) { collection.Add(value); /* fall back to append */ }","preventionTips":["Never use IndexOf result (-1 when absent) directly as an insert index.","Clamp computed indices with Math.Max(0, ...).","Prefer Add or InsertAfter/InsertBefore over raw index insertion."],"tags":["wpf","index","out-of-range"],"backgroundTag":"index-out-of-range","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-22T01:17:13.364Z"}