Skip to content

Conversation

@konard
Copy link
Member

@konard konard commented Sep 13, 2025

🐛 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 GetElementOrDefault and TryGetElement methods in GenericArrayExtensions.cs. The methods only checked:

array != null && array.Length > index

When index < 0, this condition would still be true (since array length is always positive), but accessing array[index] would throw IndexOutOfRangeException.

✅ Solution

Added proper bounds checking by including index >= 0 in all affected methods:

Before:

array != null && array.Length > index

After:

array != null && index >= 0 && array.Length > index

🔧 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

  • Added comprehensive test GetElementWithNegativeIndexTest to verify negative indices behavior
  • Added experiment demonstrating the fix works correctly
  • All existing tests continue to pass
  • Methods now gracefully handle negative indices by returning default values

📊 Test Results

Test Run Successful.
Total tests: 21
     Passed: 21

The fix ensures that:

  • Negative indices return default values instead of throwing exceptions
  • TryGetElement returns false with default element for negative indices
  • All positive valid/invalid indices continue to work as before

🤖 Generated with Claude Code

Adding CLAUDE.md with task information for AI processing.
This file will be removed when the task is complete.

Issue: #122
@konard konard self-assigned this Sep 13, 2025
…ensions

- Add bounds checking for negative indices in GetElementOrDefault methods
- Add bounds checking for negative indices in TryGetElement methods
- Both int and long versions of methods now properly handle index < 0
- Add comprehensive tests for negative index scenarios
- Add experiment demonstrating the fix works correctly

Previously, negative indices would cause IndexOutOfRangeException when accessing array[index].
Now negative indices return default values or false as expected.

Fixes #122

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
@konard konard changed the title [WIP] Fix exception throw in TryGetValue Fix IndexOutOfRangeException when using negative indices in array extensions Sep 13, 2025
@konard konard marked this pull request as ready for review September 13, 2025 12:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix exception throw in TryGetValue

2 participants