{"record":{"id":"a53f48212d473144","repo":"dotnet/wpf","slug":"sr-format-sr-markupwriter-cannotserializenestedpublictype","errorCode":null,"errorMessage":"SR.Format(SR.MarkupWriter_CannotSerializeNestedPublictype, type.ToString())","messagePattern":"SR\\.Format\\(SR\\.MarkupWriter_CannotSerializeNestedPublictype, type\\.ToString\\(\\)\\)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Markup/Primitives/MarkupWriter.cs","lineNumber":143,"sourceCode":"                writer.Flush();\n            }\n        }\n\n        /// <summary>\n        /// Throws an exception if the given type cannot be serialized because it is\n        /// 1) not public\n        /// 2) a nested-public\n        /// 3) a generic type\n        /// </summary>\n        /// <param name=\"type\">\n        /// The type to be checked\n        /// </param>\n        internal static void VerifyTypeIsSerializable(Type type)\n        {\n            // Check the type to make sure that it is not a nested type, that it is public, and that it is not generic\n            if (type.IsNestedPublic)\n            {\n                throw new InvalidOperationException( SR.Format( SR.MarkupWriter_CannotSerializeNestedPublictype, type.ToString() ));\n            }\n            if (!type.IsPublic )\n            {\n                throw new InvalidOperationException( SR.Format( SR.MarkupWriter_CannotSerializeNonPublictype, type.ToString() ));\n            }\n            if (type.IsGenericType)\n            {\n                throw new InvalidOperationException( SR.Format( SR.MarkupWriter_CannotSerializeGenerictype, type.ToString() ));\n            }\n        }\n\n        #region Internal Implementation\n        internal MarkupWriter(XmlWriter writer)\n        {\n            _writer = writer;\n            _xmlTextWriter = writer as XmlTextWriter;\n        }\n","sourceCodeStart":125,"sourceCodeEnd":161,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Markup/Primitives/MarkupWriter.cs#L125-L161","documentation":"MarkupWriter.VerifyTypeIsSerializable throws this InvalidOperationException when asked to serialize a type that is a nested public type (type.IsNestedPublic). XAML serialization in WPF only supports top-level public types, because a nested type cannot be referenced unambiguously in generated XAML. This guard runs at the start of WriteItem for every type being written.","triggerScenarios":"Calling MarkupWriter.WriteItem (directly or via XamlWriter.Save) on an object whose runtime type is a public class declared inside another class.","commonSituations":"Developers model data objects as classes nested inside a Window, App, or ViewModel class and then call XamlWriter.Save on them; sample code often nests small data classes for convenience.","solutions":["Move the nested public type to the namespace level (declare it outside the containing class) so it becomes a top-level public type.","If the nested type must stay nested, serialize via a surrogate top-level wrapper type instead.","Replace XamlWriter.Save with a custom serializer (DataContractSerializer, JSON) for types the XAML writer cannot handle."],"exampleFix":"// before\npublic class Window1 : Window {\n    public class MyData { public string Name { get; set; } }\n    void Save(object o) { XamlWriter.Save(o); } // InvalidOperationException: CannotSerializeNestedPublictype\n}\n// after\npublic class MyData { public string Name { get; set; } }\npublic class Window1 : Window {\n    void Save(object o) { XamlWriter.Save(o); }\n}","handlingStrategy":"validation","validationCode":"static bool IsXamlSerializable(Type t) =>\n    t != null && !t.IsNested && t.IsPublic && !t.IsGenericType;\n// before saving: if (!IsXamlSerializable(obj.GetType())) ...","typeGuard":"static bool IsTopLevelPublic(Type t) => !t.IsNested && t.IsPublic;","tryCatchPattern":"try { XamlWriter.Save(obj, stream); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"nested\"))\n{\n    // fall back to another serializer or move the type\n}","preventionTips":["Never declare data types nested inside classes if they will be XAML-serialized.","Keep serializable DTOs as top-level public types in their own files.","Add a unit test that runs VerifyTypeIsSerializable-equivalent checks on all serializable model types."],"tags":["wpf","xaml","serialization","reflection"],"backgroundTag":"unsupported-operation","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"}