Skip to content

Commit 0d0f99d

Browse files
committed
Fix edge case regarding foreach item adding
1 parent c220dcd commit 0d0f99d

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

DictionaryList/DictionaryList.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,11 @@ public TValue this[int index]
8080
}
8181
set
8282
{
83+
if (!_issetLookup[index])
84+
{
85+
// adding items during iteration is not allowed!
86+
_version++;
87+
}
8388
_list[index] = value;
8489
_issetLookup[index] = true;
8590
}

DictionaryListTest/Tests.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,5 +205,15 @@ public void ListCannotAddItemsDuringForeach()
205205
_dictList.Add(9);
206206
}
207207
});
208+
209+
Assert.Throws<InvalidOperationException>(() =>
210+
{
211+
_dictList.UnsetAt(1);
212+
foreach (var _ in _dictList)
213+
{
214+
// it should somehow throw the exception during iteration
215+
_dictList[1] = 4;
216+
}
217+
});
208218
}
209219
}

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ But still, here is a table outlining the performances when `N = 100000`:
162162
| Remove Many Items In-place (memory) | 0 B | 48 B | 0 B | 312 B |
163163
| Remove Many Items w/ LINQ (speed) | 104 ms ⭐ | 793 ms 👌 | 885 ms | 1693 ms |
164164
| Remove Many Items w/ LINQ (memory) | 198072 B ⭐ | 529280 B 👌 | 673168 B | 1473296 B |
165-
| Add Items During `foreach` || | ❌ new key ||
165+
| Add Items During `foreach` ||new key | ❌ new key ||
166166
| Emit Key/Index During `foreach` | 🤷 [1] | ✔️ | ✔️ | ✔️ |
167167
| Replace Items During `foreach` | 🤷 [1] | ✔️ | ✔️ | ❌ if key exists |
168168
| Remove Items During `foreach` || ✔️ | ✔️ ||

0 commit comments

Comments
 (0)