Skip to content
Code quality Reviewed 2026-09-13

Overwrite Collection Element

What does this mean ?

Two consecutive writes to the same ordinary collection slot may discard the first value before anything reads it. This often signals an incorrect key/index or unnecessary initialization. Replacing an existing value can also be intentional; it is not inherently unsafe.

What can happen ?

An expected entry may be lost or the program may perform unnecessary work. Property setters, custom collections and expressions used to compute values can have side effects, so removing a write without reviewing those effects can change behavior.

Recommendation

Determine whether the intended result is one final value, two separate entries or a controlled replacement. Use the appropriate index/key and test that state. In C#, Dictionary.Add and the indexer differ: Add rejects an existing key while the indexer replaces it. Do not casually swap them without preserving the contract.

Sample Code

// Suspicious: the first ordinary list value is immediately discarded.
items[index] = "draft";
items[index] = "ready";

// Clearer when only the final state is intended.
items[index] = "ready";
// Two separate fields when both values are required.
const item = { previousStatus: 'draft', currentStatus: 'ready' };

These are local state examples. Concurrent lost updates need synchronization or transaction controls beyond removing a duplicate assignment.

Regression checks

Assert the intended final entries and key count. Test an existing dictionary key if insertion versus replacement matters. Check that removing an earlier write does not remove a required side effect or audit event.

References