{"record":{"id":"47dd92bb56d2ea98","repo":"dotnet/wpf","slug":"indexoutofrangeexception","errorCode":null,"errorMessage":"IndexOutOfRangeException","messagePattern":"IndexOutOfRangeException","errorType":"exception","errorClass":"IndexOutOfRangeException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/Media/Imaging/WriteableBitmap.cs","lineNumber":502,"sourceCode":"\n            // We accept arrays of arbitrary value types - but not reference types.\n            if (elementType == null || !elementType.IsValueType)\n            {\n                throw new ArgumentException(SR.Image_InvalidArrayForPixel);\n            }\n            \n            checked\n            {\n                uint offsetInBytes = (uint)offset * (uint)elementSize;\n                if (offsetInBytes >= sourceBufferSize)\n                {\n                    // Backwards compat:\n                    //\n                    // The original code would throw an exception deeper in\n                    // the code when it indexed off the end of the array.  We\n                    // now check earlier (compat break) but throw the same\n                    // exception.\n                    throw new IndexOutOfRangeException();\n                }\n\n                // Backwards-Compat:\n                //\n                // The \"sourceRect\" is actually a \"destinationRect\", as in it\n                // refers to the location where the contents are written.\n                //\n                // This method presumes that the pixels are copied from the\n                // the specified offset (element count) in the source buffer, and\n                // that no sub-byte pixel formats are used.  We handle the offset\n                // later.\n                int destinationX = sourceRect.X;\n                int destinationY = sourceRect.Y;\n                sourceRect.X = 0;\n                sourceRect.Y = 0;\n\n                // Get the address of the data in the array by pinning it.\n                unsafe","sourceCodeStart":484,"sourceCodeEnd":520,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/Media/Imaging/WriteableBitmap.cs#L484-L520","documentation":"This is an explicit backwards-compatibility IndexOutOfRangeException. Historically the pixel copy indexed off the end of the source array and the CLR threw; the library now detects the buffer-too-small condition up front and throws the same exception type to preserve old behavior.","triggerScenarios":"Calling WritePixels where the supplied source buffer (after stride, offset, and sourceRect extents are computed) is smaller than required: sourceBufferSize <= offsetInBytes, i.e., the array cannot supply sourceRect.Height rows of stride bytes.","commonSituations":"Off-by-one in stride computation (width * bytesPerPixel), forgetting the offset when writing partial rows, or reusing a small scratch buffer with a larger sourceRect.","solutions":["Ensure sourceBuffer.Length >= offsetInBytes + stride * sourceRect.Height (in elements).","Compute stride as width * bytesPerPixel rounded up to 4 bytes if required by the format.","Shrink sourceRect or enlarge the array before calling WritePixels.","Catch IndexOutOfRangeException at the call site to report buffer-size bugs clearly."],"exampleFix":"// before\nbitmap.WritePixels(rect, new byte[stride * (rect.Height - 1)], stride, 0);\n// after\nbitmap.WritePixels(rect, new byte[stride * rect.Height + offset], stride, offset);","handlingStrategy":"validation","validationCode":"int bpp = bitmap.Format.BitsPerPixel / 8;\nint offsetInBytes = offset * Marshal.SizeOf(elementType);\nlong required = (long)stride * sourceRect.Height + offsetInBytes;\nif (sourceBuffer.Length * Marshal.SizeOf(elementType) < required) throw new IndexOutOfRangeException(\"source buffer too small for sourceRect\");","typeGuard":null,"tryCatchPattern":"try { bitmap.WritePixels(rect, buf, stride, offset); } catch (IndexOutOfRangeException) { /* grow buffer and retry */ }","preventionTips":["Compute required size = stride * rect.Height (+ offset) before calling","Round stride up if the format requires 4-byte alignment","Unit-test WritePixels with boundary rect sizes"],"tags":["wpf","bitmap","index-out-of-range","buffer-size"],"backgroundTag":"index-out-of-bounds","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"}