{"record":{"id":"7a53426daecbccac","repo":"dotnet/wpf","slug":"sr-collection-badtype-collectionhelper","errorCode":null,"errorMessage":"SR.Collection_BadType","messagePattern":"SR\\.Collection_BadType","errorType":"validation","errorClass":"System.ArgumentException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/WpfGfx/codegen/mcg/helpers/CollectionHelper.cs","lineNumber":1168,"sourceCode":"                    /// </summary>\n                    internal [[type]] Internal_GetItem(int i)\n                    {\n                        return _collection[i];\n                    }\n\n                    [[onInheritanceContextChangedCoreMethod]]\n\n                    #endregion\n\n                    #region Private Helpers\n\n                    private [[type]] Cast(object value)\n                    {\n                        ArgumentNullException.ThrowIfNull(value);\n\n                        if (!(value is [[type]]))\n                        {\n                            throw new System.ArgumentException(SR.Format(SR.Collection_BadType, this.GetType().Name, value.GetType().Name, \"[[type]]\"));\n                        }\n\n                        return ([[type]]) value;\n                    }\n\n                    // IList.Add returns int and IList<T>.Add does not. This\n                    // is called by both Adds and IList<T>'s just ignores the\n                    // integer\n                    private int AddHelper([[type]] value)\n                    {\n                        int index = AddWithoutFiringPublicEvents(value);\n\n                        // AddAtWithoutFiringPublicEvents incremented the version\n\n                        WritePostscript();\n\n                        return index;\n                    }","sourceCodeStart":1150,"sourceCodeEnd":1186,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/WpfGfx/codegen/mcg/helpers/CollectionHelper.cs#L1150-L1186","documentation":"This ArgumentException is thrown by the strongly-typed Cast(object) method that CollectionHelper generates for each typed collection in the WPF mcg codegen tool. IList.Add/IList.Insert receive System.Object, and the generator wraps them with a runtime type check so that only instances of the collection's element type are accepted. If the value is not assignable to [[type]], the collection rejects it rather than storing a wrongly-typed item.","triggerScenarios":"Calling Add/Insert/Contains/Indexer-set on a generated typed collection through its non-generic IList interface with an object that is not of (or derived from) the declared element type, e.g. `((IList)stringCollection).Add(42)`.","commonSituations":"Reflection-based or XAML/BAML deserialization code inserting values of the wrong type; passing a base-type collection an incompatible item; API version changes that changed a collection's element type while caller code still adds old values.","solutions":["Check the value's type before adding: only insert instances of the collection's declared element type.","Convert or map the value to the expected element type prior to the Add/Insert call.","If the collection type is wrong for your data, use a collection whose element type matches."],"exampleFix":"// before\n((IList)collection).Add(someObject); // throws if someObject is not [[type]]\n// after\nif (someObject is [[type]] typed)\n{\n    ((IList)collection).Add(typed);\n}","handlingStrategy":"type-guard","validationCode":"if (value == null) throw new ArgumentNullException(nameof(value));\nif (!(value is [[type]]))\n    throw new ArgumentException($\"Expected [[type]], got {value.GetType().Name}\");","typeGuard":"static bool Is acceptableItemType(object value) => value is [[type]];\n// pattern-match before adding:\nif (value is [[type]] typed) ((IList)collection).Add(typed);","tryCatchPattern":"try { ((IList)collection).Add(value); }\ncatch (ArgumentException ex) when (ex.Message.Contains(\"wrong type\") || ex.Message.Contains(\"BadType\")) { /* convert or log the type mismatch */ }","preventionTips":["Use the generic collection API (IList<T>/Add(T)) instead of the non-generic IList overload.","Validate element types at deserialization boundaries.","Keep element-type declarations in sync with the data you insert."],"tags":["argumentexception","type-mismatch","collection","wpf-codegen"],"backgroundTag":"type-mismatch","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-21T21:30:21.729Z"}