{"record":{"id":"affeaa19b383a658","repo":"dotnet/wpf","slug":"sr-cannotserializeinvalidinstance","errorCode":null,"errorMessage":"SR.CannotSerializeInvalidInstance","messagePattern":"SR\\.CannotSerializeInvalidInstance","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Annotations/Annotation.cs","lineNumber":196,"sourceCode":"        {\n            ArgumentNullException.ThrowIfNull(writer);\n\n            //fire trace event\n            EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordAnnotation, EventTrace.Event.SerializeAnnotationBegin);\n            try\n            {\n                if (String.IsNullOrEmpty(writer.LookupPrefix(AnnotationXmlConstants.Namespaces.CoreSchemaNamespace)))\n                {\n                    writer.WriteAttributeString(AnnotationXmlConstants.Prefixes.XmlnsPrefix, AnnotationXmlConstants.Prefixes.CoreSchemaPrefix, null, AnnotationXmlConstants.Namespaces.CoreSchemaNamespace);\n                }\n                if (String.IsNullOrEmpty(writer.LookupPrefix(AnnotationXmlConstants.Namespaces.BaseSchemaNamespace)))\n                {\n                    writer.WriteAttributeString(AnnotationXmlConstants.Prefixes.XmlnsPrefix, AnnotationXmlConstants.Prefixes.BaseSchemaPrefix, null, AnnotationXmlConstants.Namespaces.BaseSchemaNamespace);\n                }\n\n                if (_typeName == null)\n                {\n                    throw new InvalidOperationException(SR.CannotSerializeInvalidInstance);\n                }\n\n                // XmlConvert.ToString is [Obsolete]\n#pragma warning disable 0618\n\n                writer.WriteAttributeString(AnnotationXmlConstants.Attributes.Id, XmlConvert.ToString(_id));\n                writer.WriteAttributeString(AnnotationXmlConstants.Attributes.CreationTime, XmlConvert.ToString(_created));\n                writer.WriteAttributeString(AnnotationXmlConstants.Attributes.LastModificationTime, XmlConvert.ToString(_modified));\n\n#pragma warning restore 0618\n\n                writer.WriteStartAttribute(AnnotationXmlConstants.Attributes.TypeName);\n                writer.WriteQualifiedName(_typeName.Name, _typeName.Namespace);\n                writer.WriteEndAttribute();\n\n                if (_authors != null && _authors.Count > 0)\n                {\n                    writer.WriteStartElement(AnnotationXmlConstants.Elements.AuthorCollection, AnnotationXmlConstants.Namespaces.CoreSchemaNamespace);","sourceCodeStart":178,"sourceCodeEnd":214,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Annotations/Annotation.cs#L178-L214","documentation":"WriteXml throws InvalidOperationException with SR.CannotSerializeInvalidInstance when _typeName is null, meaning the Annotation instance is in an invalid (uninitialized) state. The type attribute is mandatory in the Annotation XML schema, so an annotation without a type cannot be serialized.","triggerScenarios":"Calling Annotation.WriteXml (directly or via XmlSerializer) on an Annotation that was constructed without a valid annotationType or whose type was never set by ReadXml.","commonSituations":"Serializing a default/uninitialized Annotation object; XmlSerializer pipelines that include half-initialized annotations in the graph; skipping the constructor validation path by using serialization-friendly construction.","solutions":["Only serialize Annotation instances that were constructed with a valid non-null XmlQualifiedName type","Check the instance is fully initialized before adding it to an annotation store/serializer","Catch InvalidOperationException in serialization code and skip or report the invalid annotation"],"exampleFix":"// before\nvar ann = new Annotation(); // default instance, no type\nserializer.Serialize(stream, ann);\n// after\nvar ann = new Annotation(new XmlQualifiedName(\"Note\", \"http://schemas.example.com/ann\"), Guid.NewGuid(), DateTime.UtcNow, DateTime.UtcNow);\nserializer.Serialize(stream, ann);","handlingStrategy":"try-catch","validationCode":"if (annotation == null)\n    throw new InvalidOperationException(\"Cannot serialize null annotation\");\n// ensure the instance was constructed with a valid type\nvar valid = !string.IsNullOrEmpty(annotation.AnnotationType?.Name);\nif (!valid) throw new InvalidOperationException(\"Annotation is not fully initialized for serialization\");","typeGuard":"bool IsSerializableAnnotation(Annotation a) => a != null && a.AnnotationType != null && !string.IsNullOrEmpty(a.AnnotationType.Name);","tryCatchPattern":"try\n{\n    serializer.Serialize(stream, annotation);\n}\ncatch (InvalidOperationException ex)\n{\n    logger.LogError(ex, \"Skipping annotation that cannot be serialized (missing type)\");\n}","preventionTips":["Only serialize annotations produced through the public constructors or a successful ReadXml","Avoid default-constructed Annotation objects in object graphs handed to XmlSerializer","Validate annotation stores after deserialization before re-serializing"],"tags":["wpf","annotations","xml-serialization"],"backgroundTag":"json-serialization-failed","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"}