{"record":{"id":"31ca530917c4c267","repo":"XINCGer/Unity3DTraining","slug":"key-already-exists-in-map","errorCode":null,"errorMessage":"Key already exists in map","messagePattern":"Key already exists in map","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"NetWorkAndResources/Socket_Protobuff/Assets/Plugins/Google.Protobuf/Collections/MapField.cs","lineNumber":115,"sourceCode":"        public void Add(TKey key, TValue value)\n        {\n            // Validation of arguments happens in ContainsKey and the indexer\n            if (ContainsKey(key))\n            {\n                throw new ArgumentException(\"Key already exists in map\", \"key\");\n            }\n            this[key] = value;\n        }","sourceCodeStart":97,"sourceCodeEnd":133,"githubUrl":"https://github.com/XINCGer/Unity3DTraining/blob/016f98412ea5e11756b286736f479b66ab6216d5/NetWorkAndResources/Socket_Protobuff/Assets/Plugins/Google.Protobuf/Collections/MapField.cs#L97-L133","documentation":"MapField.Add throws ArgumentException when the supplied key is already present in the map, leaving the map unchanged. Add is strictly insert-only: unlike the indexer, it never overwrites, so a duplicate key — including re-adding the same key twice, e.g. in Clone which copies entries via Add — fires this guard.","triggerScenarios":"Calling Add(key, value) when ContainsKey(key) is already true — e.g. adding a duplicate key to a MapField, or Clone re-inserting an existing entry.","commonSituations":"Populating a protobuf map field from data that may contain duplicate keys; copying entries between MapField instances with Add instead of the indexer; merging two maps without checking for key collisions.","solutions":["Check ContainsKey(key) before calling Add, or wrap Add in try/catch for ArgumentException.","Use the indexer mapField[key] = value when the intent is to insert-or-replace.","Deduplicate the source data (e.g. with a HashSet or GroupBy) before populating the map.","In Clone-like copy loops, use the indexer so re-copying existing keys overwrites instead of throwing."],"exampleFix":"if (!mapField.ContainsKey(key)) { mapField.Add(key, value); } // or simply: mapField[key] = value; to overwrite.","handlingStrategy":"validation","validationCode":"if (map.ContainsKey(key)) map[key] = value; else map.Add(key, value);","typeGuard":null,"tryCatchPattern":"try { map.Add(key, value); } catch (ArgumentException) { map[key] = value; /* or log duplicate */ }","preventionTips":["Treat Add as insert-only and reserve it for keys known to be new.","Prefer the indexer for upsert semantics.","Validate/deduplicate key sources before bulk insertion."],"tags":["protobuf","csharp","duplicate-key"],"backgroundTag":"invalid-argument-value","analyzedSha":"016f98412ea5e11756b286736f479b66ab6216d5","analyzedAt":"2026-09-12T01:08:58.711Z","contentChangedAt":"2026-09-12T01:08:58.711Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}