{"record":{"id":"15bd01742038de68","repo":"JamesNK/Newtonsoft.Json","slug":"the-value-0-is-not-of-type-1-and-cannot-be","errorCode":null,"errorMessage":"The value '{0}' is not of type '{1}' and cannot be used in this generic collection.","messagePattern":"The value '(.+?)' is not of type '(.+?)' and cannot be used in this generic collection\\.","errorType":"validation","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs","lineNumber":304,"sourceCode":"\n        object ICollection.SyncRoot\n        {\n            get\n            {\n                if (_syncRoot == null)\n                {\n                    Interlocked.CompareExchange(ref _syncRoot, new object(), null);\n                }\n\n                return _syncRoot;\n            }\n        }\n\n        private static void VerifyValueType(object? value)\n        {\n            if (!IsCompatibleObject(value))\n            {\n                throw new ArgumentException(\"The value '{0}' is not of type '{1}' and cannot be used in this generic collection.\".FormatWith(CultureInfo.InvariantCulture, value, typeof(T)), nameof(value));\n            }\n        }\n\n        private static bool IsCompatibleObject(object? value)\n        {\n            if (!(value is T) && (value != null || (typeof(T).IsValueType() && !ReflectionUtils.IsNullableType(typeof(T)))))\n            {\n                return false;\n            }\n\n            return true;\n        }\n\n        public object UnderlyingCollection => (object)_genericCollection! ?? _list!;\n    }\n}","sourceCodeStart":286,"sourceCodeEnd":320,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs#L286-L320","documentation":"CollectionWrapper<T> is strongly typed to element type T. The non-generic IList path (Add, Insert, indexer set) calls VerifyValueType (CollectionWrapper.cs:300-306), which uses IsCompatibleObject to check the value is assignable to T. If the runtime type isn't compatible (e.g. adding an int into a List<string>), it throws ArgumentException with the value and the expected type T.","triggerScenarios":"Deserializing a JSON array whose element CLR type (after conversion) doesn't match the target collection's element type T, with the value flowing through the IList.Add/Insert/indexer-set path. Also triggered by a custom converter returning the wrong element type.","commonSituations":"Mixed-type JSON arrays deserialized into strongly-typed List<T>; polymorphic payloads without TypeNameHandling; custom JsonConverter returning a type that isn't T; schema drift where a field changed type.","solutions":["Align the JSON array element type with the collection's element type T (e.g. send numbers for List<int>).","Register a JsonConverter that converts each element to T before it reaches the collection.","Widen the element type (use List<object> or a base type) if the array is heterogeneous.","Enable TypeNameHandling and emit $type for polymorphic arrays.","Validate the JSON payload against the expected schema before deserialization."],"exampleFix":"// before\npublic List<int> Ids { get; set; }  // JSON: [\"42\",\"43\"] -> strings into int list\n// after\npublic List<int> Ids { get; set; }  // JSON: [42,43]\n//   OR add a converter that parses numeric strings to int","handlingStrategy":"type-guard","validationCode":"// Validate each element matches T before inserting via the non-generic IList path.\nstatic void SafeAdd<T>(System.Collections.Generic.ICollection<T> c, object value) {\n    if (value is T t || (value == null && default(T) == null)) c.Add(t);\n    else throw new InvalidOperationException($\"{value?.GetType()} is not compatible with {typeof(T)}.\");\n}","typeGuard":"static bool IsCompatible<T>(object? value) => value is T || (value == null && (!typeof(T).IsValueType || System.Nullable.GetUnderlyingType(typeof(T)) != null));","tryCatchPattern":"try { list.Add(value); } catch (ArgumentException ex) when (ex.Message.Contains(\"is not of type\")) { /* log schema mismatch; coerce or skip */ }","preventionTips":["Validate JSON array element types against the target element type before deserialization.","Use strongly-typed models that match the JSON shape.","Register converters that return the exact element type T.","Enable TypeNameHandling for polymorphic arrays."],"tags":["collections","type-mismatch","serialization","newtonsoft-json"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}