{"record":{"id":"6728062ae1b9e89d","repo":"TheAlgorithms/C-Sharp","slug":"key-already-exists","errorCode":null,"errorMessage":"Key already exists","messagePattern":"Key already exists","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"DataStructures/Hashing/HashTable.cs","lineNumber":140,"sourceCode":"    /// If the number of elements in the hash table is greater than or equal to the threshold, the hash table is resized.\n    /// </remarks>\n    public void Add(TKey? key, TValue? value)\n    {\n        if (EqualityComparer<TKey>.Default.Equals(key, default))\n        {\n            throw new ArgumentNullException(nameof(key));\n        }\n\n        if (size >= threshold)\n        {\n            Resize();\n        }\n\n        var index = GetIndex(key);\n        if (entries[index] != null &&\n            EqualityComparer<TKey>.Default.Equals(entries[index]!.Key!, key))\n        {\n            throw new ArgumentException(\"Key already exists\");\n        }\n\n        if (EqualityComparer<TValue>.Default.Equals(value, default))\n        {\n            throw new ArgumentNullException(nameof(value));\n        }\n\n        entries[index] = new Entry<TKey, TValue>(key!, value!);\n        size++;\n    }\n\n    /// <summary>\n    /// Removes the key-value pair associated with the specified key.\n    /// </summary>\n    /// <param name=\"key\">Key to remove.</param>\n    /// <returns>True if the key-value pair was removed, false otherwise.</returns>\n    /// <exception cref=\"ArgumentNullException\">Thrown when <paramref name=\"key\"/> is null.</exception>\n    /// <remarks>","sourceCodeStart":122,"sourceCodeEnd":158,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/DataStructures/Hashing/HashTable.cs#L122-L158","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"// before\ntable.Add(key, value);\n// after\nif (!table.ContainsKey(key)) table.Add(key, value);","handlingStrategy":"validation","validationCode":"if (table.ContainsKey(key))\n    throw new InvalidOperationException($\"Key '{key}' already present\");","typeGuard":null,"tryCatchPattern":"try { table.Add(key, value); }\ncatch (ArgumentException ex) when (ex.Message == \"Key already exists\")\n{\n    // treat as duplicate insert; optionally update via Remove+Add\n}","preventionTips":["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."],"tags":["duplicate-key","hash-table","argument-exception"],"backgroundTag":"invalid-argument-value","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}