XINCGer/Unity3DTraining · error · ArgumentException
Key already exists in map
Error message
Key already exists in map
What it means
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.
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.
Example fix
if (!mapField.ContainsKey(key)) { mapField.Add(key, value); } // or simply: mapField[key] = value; to overwrite. Defensive patterns
Strategy: validation
Validate before calling
if (map.ContainsKey(key)) map[key] = value; else map.Add(key, value);
Try / catch
try { map.Add(key, value); } catch (ArgumentException) { map[key] = value; /* or log duplicate */ } Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
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
- Offset must be within the buffer
- Length must be non-negative and within the buffer
- Stream.Read returned a negative count
- SpaceLeft can only be called on CodedOutputStreams that are…
- Key is null
AI-assisted analysis of XINCGer/Unity3DTraining@016f98412e (2026-09-12).
Data as JSON: /api/errors/31ca530917c4c267.
Report an issue: GitHub.
Appendix: source
Thrown at NetWorkAndResources/Socket_Protobuff/Assets/Plugins/Google.Protobuf/Collections/MapField.cs:115
public void Add(TKey key, TValue value)
{
// Validation of arguments happens in ContainsKey and the indexer
if (ContainsKey(key))
{
throw new ArgumentException("Key already exists in map", "key");
}
this[key] = value;
}View on GitHub (pinned to 016f98412e)