{"record":{"id":"632856288e5ce671","repo":"louthy/language-ext","slug":"key-already-exists-in-map-change-key","errorCode":null,"errorMessage":"Key already exists in map: {change.Key}","messagePattern":"Key already exists in map: (.+?)","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"LanguageExt.Core/Immutable Collections/TrieMap/TrieMap.cs","lineNumber":2307,"sourceCode":"        public (int CountDelta, Node Node, V? Old, bool Changed) Update((UpdateType Type, bool Mutate) env, (K Key, V Value) change, uint hash, Sec section)\n        {\n            // var hashIndex = Bit.Get(hash, section);\n            // var mask = Mask(hashIndex);\n            var mask = (uint)(1 << (int)((hash & (uint)(Sec.Mask << section.Offset)) >> section.Offset));\n\n            //if (Bit.Get(EntryMap, mask))\n            if((EntryMap & mask) == mask)\n            {\n                //var entryIndex = Index(EntryMap, mask);\n                var entryIndex   = BitCount((int)EntryMap & ((int)mask - 1));\n                var currentEntry = Items[entryIndex];\n\n                if (EqK.Equals(currentEntry.Key, change.Key))\n                {\n                    if (env.Type == UpdateType.Add)\n                    {\n                        // Key already exists - so it's an error to add again\n                        throw new ArgumentException($\"Key already exists in map: {change.Key}\");\n                    }\n                    else if (env.Type == UpdateType.TryAdd)\n                    {\n                        // Already added, so we don't continue to try\n                        return (0, this, default, false);\n                    }\n\n                    var (newItems, old) = SetItem(Items, entryIndex, change, env.Mutate);\n                    return (0, new Entries(EntryMap, NodeMap, newItems, Nodes), old.Value, true);\n                }\n                else\n                {\n                    if (env.Type == UpdateType.SetItem)\n                    {\n                        // Key must already exist to set it\n                        throw new ArgumentException($\"Key already exists in map: {change.Key}\");\n                    }\n                    else if (env.Type == UpdateType.TrySetItem)","sourceCodeStart":2289,"sourceCodeEnd":2325,"githubUrl":"https://github.com/louthy/language-ext/blob/2f0e3628242889774d4141960a35671a0280051f/LanguageExt.Core/Immutable Collections/TrieMap/TrieMap.cs#L2289-L2325","documentation":"During a TrieMap update traversal, when the key is found and the update type is Add (not SetItem/TryAdd), the library throws because Add is defined as insert-only: adding an existing key is an error. TryAdd silently keeps the existing entry instead. This enforces the semantic difference between Add and SetItem on the immutable map.","triggerScenarios":"Calling map.Add(key, value) (or union/duplicate-preserving bulk adds that route UpdateType.Add) on a TrieMap that already contains an equal key under its EqK comparer.","commonSituations":"Building a map from user-supplied key/value pairs containing duplicates; merging two maps with overlapping keys using Add semantics; case differences that a case-sensitive comparer treats as duplicates of different intent.","solutions":["Use AddOrUpdate(key, value) or SetItem when overwriting is intended","Use TryAdd when you want to keep the first value and ignore duplicates","Deduplicate or group the source sequence before adding","Check ContainsKey before Add if the branch logic requires it"],"exampleFix":"// before\nmap = map.Add(key, value);\n// after\nmap = map.AddOrUpdate(key, value);","handlingStrategy":"validation","validationCode":"if (map.ContainsKey(key)) map = map.SetItem(key, value); else map = map.Add(key, value);","typeGuard":null,"tryCatchPattern":"try { map = map.Add(key, value); }\ncatch (ArgumentException) { map = map.SetItem(key, value); }","preventionTips":["Use AddOrUpdate for upsert-style writes","Use TryAdd when duplicates should be ignored","Deduplicate bulk inputs before Add"],"tags":["immutable-collections","duplicate-key","argumentexception"],"backgroundTag":"key-already-exists","analyzedSha":"2f0e3628242889774d4141960a35671a0280051f","analyzedAt":"2026-09-15T03:31:55.716Z","contentChangedAt":"2026-09-15T03:31:55.716Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}