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

  1. Check ContainsKey(key) before calling Add, or wrap Add in try/catch for ArgumentException.
  2. Use the indexer mapField[key] = value when the intent is to insert-or-replace.
  3. Deduplicate the source data (e.g. with a HashSet or GroupBy) before populating the map.
  4. 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

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


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)