Fix IndexOutOfRangeException when using negative indices in array extensions #158
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
🐛 Bug Fix
This pull request fixes issue #122 where negative indices passed to array extension methods would cause
IndexOutOfRangeException.📋 Issue Reference
Fixes #122
🔍 Root Cause
The issue was in the
GetElementOrDefaultandTryGetElementmethods inGenericArrayExtensions.cs. The methods only checked:When
index < 0, this condition would still betrue(since array length is always positive), but accessingarray[index]would throwIndexOutOfRangeException.✅ Solution
Added proper bounds checking by including
index >= 0in all affected methods:Before:
After:
🔧 Methods Fixed
GetElementOrDefault<T>(this T[] array, int index)GetElementOrDefault<T>(this T[] array, long index)TryGetElement<T>(this T[] array, int index, out T element)TryGetElement<T>(this T[] array, long index, out T element)🧪 Testing
GetElementWithNegativeIndexTestto verify negative indices behavior📊 Test Results
The fix ensures that:
TryGetElementreturnsfalsewith default element for negative indices🤖 Generated with Claude Code