{"record":{"id":"8677ead134e312c3","repo":"stride3d/stride","slug":"cannot-add-item-with-key-keyvalue-key-to-dictionary-of-type","errorCode":null,"errorMessage":"Cannot add item with key [{keyValue.Key}] to dictionary of type [{objectContext.Descriptor}]:\n{ex.Message}","messagePattern":"Cannot add item with key \\[(.+?)\\] to dictionary of type \\[(.+?)\\]:\n(.+?)","errorType":"exception","errorClass":"YamlException","httpStatus":null,"severity":"error","filePath":"sources/core/Stride.Core.Yaml/Serialization/Serializers/DictionarySerializer.cs","lineNumber":163,"sourceCode":"\n            var reader = objectContext.Reader;\n            while (!reader.Accept<MappingEnd>())\n            {\n                var currentDepth = objectContext.Reader.CurrentDepth;\n                var startParsingEvent = objectContext.Reader.Parser.Current;\n\n                try\n                {\n                    // Read key and value\n                    var keyValue = ReadDictionaryItem(ref objectContext, new KeyValuePair<Type, Type>(dictionaryDescriptor.KeyType, dictionaryDescriptor.ValueType));\n                    try\n                    {\n                        dictionaryDescriptor.AddToDictionary(objectContext.Instance, keyValue.Key, keyValue.Value);\n                    }\n                    catch (Exception ex)\n                    {\n                        ex = ex.Unwrap();\n                        throw new YamlException(reader.Parser.Current.Start, reader.Parser.Current.End, $\"Cannot add item with key [{keyValue.Key}] to dictionary of type [{objectContext.Descriptor}]:\\n{ex.Message}\", ex);\n                    }\n                }\n                catch (YamlException ex)\n                {\n                    if (objectContext.SerializerContext.AllowErrors)\n                    {\n                        var logger = objectContext.SerializerContext.Logger;\n                        logger?.Warning($\"{ex.Message}, this dictionary item will be ignored\", ex);\n                        objectContext.Reader.Skip(currentDepth, startParsingEvent == objectContext.Reader.Parser.Current);\n                    }\n                    else throw;\n                }\n            }\n        }\n\n        /// <summary>\n        /// Reads a dictionary item key-value.\n        /// </summary>","sourceCodeStart":145,"sourceCodeEnd":181,"githubUrl":"https://github.com/stride3d/stride/blob/96fad776d210c221682aac1ccdf4c79dc046fc38/sources/core/Stride.Core.Yaml/Serialization/Serializers/DictionarySerializer.cs#L145-L181","documentation":"DictionarySerializer wraps any exception that occurs while adding a deserialized key/value pair into the target dictionary in a YamlException pinpointing the key-value node, preserving the underlying ex.Message. It signals the pair could not be inserted into the dictionary of that type.","triggerScenarios":"An exception thrown by dictionaryDescriptor.AddToDictionary during ReadDictionaryItems — duplicate keys when Add throws, key type conversion failure not caught earlier, or a keyed collection whose Add method rejects the entry.","commonSituations":"Duplicate keys in YAML mapping for dictionaries backed by keyed collections that disallow re-adding; key types with custom equality where deserialized key is invalid; custom dictionary subclasses with guarded Add.","solutions":["Fix or remove the offending key in the YAML document at the reported location","Ensure the dictionary type's Add/AddToDictionary can accept all serialized keys (no duplicates, valid keys)","Check the inner exception (ex.Message) for the underlying cause","Enable SerializerContext.AllowErrors if partial deserialization with skipped errors is acceptable"],"exampleFix":"// before\nsizes:\n  small: 1\n  small: 2   // duplicate key rejected by dictionary\n// after\nsizes:\n  small: 1\n  medium: 2","handlingStrategy":"try-catch","validationCode":"// Detect duplicate keys before deserialization\nvar seen = new HashSet<string>();\nforeach (var key in mappingKeys)\n    if (!seen.Add(key)) throw new YamlException(key, $\"Duplicate dictionary key '{key}'\");","typeGuard":null,"tryCatchPattern":"try\n{\n    dictSerializer.ReadYaml(ref objectContext);\n}\ncatch (YamlException ex) when (ex.Message.StartsWith(\"Cannot add item with key\"))\n{\n    logger.LogError(ex.InnerException, \"Failed to add entry at {Start}\", ex.Start);\n}","preventionTips":["Ensure unique keys in YAML mappings","Avoid custom dictionary Add overrides that reject valid entries","Check the inner exception for the underlying Add failure"],"tags":["yaml","deserialization","dictionary"],"backgroundTag":"yaml-parse-error","analyzedSha":"96fad776d210c221682aac1ccdf4c79dc046fc38","analyzedAt":"2026-09-14T02:59:31.279Z","contentChangedAt":"2026-09-14T02:59:31.279Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}