dotnet/wpf · error · InvalidOperationException

SR.CannotSerializeInvalidInstance

Error message

SR.CannotSerializeInvalidInstance

What it means

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.

Solutions

  1. Only serialize Annotation instances that were constructed with a valid non-null XmlQualifiedName type
  2. Check the instance is fully initialized before adding it to an annotation store/serializer
  3. Catch InvalidOperationException in serialization code and skip or report the invalid annotation

Example fix

// before
var ann = new Annotation(); // default instance, no type
serializer.Serialize(stream, ann);
// after
var ann = new Annotation(new XmlQualifiedName("Note", "http://schemas.example.com/ann"), Guid.NewGuid(), DateTime.UtcNow, DateTime.UtcNow);
serializer.Serialize(stream, ann);
Defensive patterns

Strategy: try-catch

Validate before calling

if (annotation == null)
    throw new InvalidOperationException("Cannot serialize null annotation");
// ensure the instance was constructed with a valid type
var valid = !string.IsNullOrEmpty(annotation.AnnotationType?.Name);
if (!valid) throw new InvalidOperationException("Annotation is not fully initialized for serialization");

Type guard

bool IsSerializableAnnotation(Annotation a) => a != null && a.AnnotationType != null && !string.IsNullOrEmpty(a.AnnotationType.Name);

Try / catch

try
{
    serializer.Serialize(stream, annotation);
}
catch (InvalidOperationException ex)
{
    logger.LogError(ex, "Skipping annotation that cannot be serialized (missing type)");
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Understand the failure class

Background: "JSON serialization failed", "not JSON serializable", "Failed to serialize": why JSON marshaling errors happen and how to fix them — this error's family across 46 libraries.

Related errors


AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14). Data as JSON: /api/errors/affeaa19b383a658. Report an issue: GitHub.

Appendix: source

Thrown at src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Annotations/Annotation.cs:196

        {
            ArgumentNullException.ThrowIfNull(writer);

            //fire trace event
            EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordAnnotation, EventTrace.Event.SerializeAnnotationBegin);
            try
            {
                if (String.IsNullOrEmpty(writer.LookupPrefix(AnnotationXmlConstants.Namespaces.CoreSchemaNamespace)))
                {
                    writer.WriteAttributeString(AnnotationXmlConstants.Prefixes.XmlnsPrefix, AnnotationXmlConstants.Prefixes.CoreSchemaPrefix, null, AnnotationXmlConstants.Namespaces.CoreSchemaNamespace);
                }
                if (String.IsNullOrEmpty(writer.LookupPrefix(AnnotationXmlConstants.Namespaces.BaseSchemaNamespace)))
                {
                    writer.WriteAttributeString(AnnotationXmlConstants.Prefixes.XmlnsPrefix, AnnotationXmlConstants.Prefixes.BaseSchemaPrefix, null, AnnotationXmlConstants.Namespaces.BaseSchemaNamespace);
                }

                if (_typeName == null)
                {
                    throw new InvalidOperationException(SR.CannotSerializeInvalidInstance);
                }

                // XmlConvert.ToString is [Obsolete]
#pragma warning disable 0618

                writer.WriteAttributeString(AnnotationXmlConstants.Attributes.Id, XmlConvert.ToString(_id));
                writer.WriteAttributeString(AnnotationXmlConstants.Attributes.CreationTime, XmlConvert.ToString(_created));
                writer.WriteAttributeString(AnnotationXmlConstants.Attributes.LastModificationTime, XmlConvert.ToString(_modified));

#pragma warning restore 0618

                writer.WriteStartAttribute(AnnotationXmlConstants.Attributes.TypeName);
                writer.WriteQualifiedName(_typeName.Name, _typeName.Namespace);
                writer.WriteEndAttribute();

                if (_authors != null && _authors.Count > 0)
                {
                    writer.WriteStartElement(AnnotationXmlConstants.Elements.AuthorCollection, AnnotationXmlConstants.Namespaces.CoreSchemaNamespace);

View on GitHub (pinned to 81131a70a4)