TheAlgorithms/C-Sharp · error · ArgumentException
Key already exists
Error message
Key already exists
What it means
HashTable.Add throws ArgumentException("Key already exists") when an entry with an equal key already occupies the computed bucket. Unlike Dictionary.Add, this table does not overwrite; duplicate insertion is treated as a programming error.
Solutions
- Check table.ContainsKey(key) before calling Add, or use it to decide update vs insert.
- Remove the existing entry first if overwrite semantics are wanted.
- Catch ArgumentException and treat it as 'already present' if that is acceptable.
Example fix
// before table.Add(key, value); // after if (!table.ContainsKey(key)) table.Add(key, value);
Defensive patterns
Strategy: validation
Validate before calling
if (table.ContainsKey(key))
throw new InvalidOperationException($"Key '{key}' already present"); Try / catch
try { table.Add(key, value); }
catch (ArgumentException ex) when (ex.Message == "Key already exists")
{
// treat as duplicate insert; optionally update via Remove+Add
} Prevention
- Check ContainsKey before Add, or model insert-or-update explicitly.
- Make import jobs idempotent (dedupe keys before inserting).
- Deduplicate source data before seeding the table in loops.
When it happens
Trigger: Calling Add twice with the same key without Remove in between, e.g. table.Add("a", 1); table.Add("a", 2); or re-running an idempotency-unsafe import that re-inserts existing keys.
Common situations: Data imports run twice; seeding a table in a loop over data containing duplicate keys; merging two datasets that share keys; retry logic re-executing an Add that already succeeded.
Understand the failure class
Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.
Related errors
- Key " " already in tree!
- Matrix must be square!
- Key " " already exists in AVL tree.
- Key " " already exists in B-Tree.
- Key " " already exists in tree!
AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13).
Data as JSON: /api/errors/6728062ae1b9e89d.
Report an issue: GitHub.
Appendix: source
Thrown at DataStructures/Hashing/HashTable.cs:140
/// If the number of elements in the hash table is greater than or equal to the threshold, the hash table is resized.
/// </remarks>
public void Add(TKey? key, TValue? value)
{
if (EqualityComparer<TKey>.Default.Equals(key, default))
{
throw new ArgumentNullException(nameof(key));
}
if (size >= threshold)
{
Resize();
}
var index = GetIndex(key);
if (entries[index] != null &&
EqualityComparer<TKey>.Default.Equals(entries[index]!.Key!, key))
{
throw new ArgumentException("Key already exists");
}
if (EqualityComparer<TValue>.Default.Equals(value, default))
{
throw new ArgumentNullException(nameof(value));
}
entries[index] = new Entry<TKey, TValue>(key!, value!);
size++;
}
/// <summary>
/// Removes the key-value pair associated with the specified key.
/// </summary>
/// <param name="key">Key to remove.</param>
/// <returns>True if the key-value pair was removed, false otherwise.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="key"/> is null.</exception>
/// <remarks>View on GitHub (pinned to 96e2905cab)