{"record":{"id":"fdc49bafbb7fa83d","repo":"dotnet/wpf","slug":"sr-cantassignrootinstance","errorCode":null,"errorMessage":"SR.CantAssignRootInstance","messagePattern":"SR\\.CantAssignRootInstance","errorType":"exception","errorClass":"XamlParseException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/System.Xaml/System/Xaml/InfosetObjects/XamlObjectWriter.cs","lineNumber":375,"sourceCode":"            // A Frame is pushed by either a AddNamespace or a WriteGet/StartObject\n            if (_context.CurrentType is not null)\n            {\n                _context.PushScope();\n            }\n\n            _context.CurrentType = xamlType;\n\n            // Don't create the Root Instance if we were given one in the settings.\n            // This is an important senario when a XamlObject loads a XamlDefinition of itself\n            // in it's constructor.  The instance is already created (that is how we got into\n            // the constructor), now don't create the first StartObject use the existing instance.\n            //\n            if ((_context.LiveDepth == 1) && (_rootObjectInstance is not null))\n            {\n                XamlType rootType = GetXamlType(_rootObjectInstance.GetType());\n                if (!rootType.CanAssignTo(_context.CurrentType))\n                {\n                    throw new XamlParseException(SR.Format(SR.CantAssignRootInstance,\n                        rootType.GetQualifiedName(), xamlType.GetQualifiedName()));\n                }\n\n                _context.CurrentInstance = _rootObjectInstance;\n                if (_context.CurrentType.IsCollection || _context.CurrentType.IsDictionary)\n                {\n                    _context.CurrentCollection = _rootObjectInstance;\n                }\n\n                Logic_BeginInit(_context);\n            }\n        }\n\n        public override void WriteEndObject()\n        {\n            ThrowIfDisposed();\n\n            // Deferring Checking","sourceCodeStart":357,"sourceCodeEnd":393,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/System.Xaml/System/Xaml/InfosetObjects/XamlObjectWriter.cs#L357-L393","documentation":"XamlParseException thrown by XamlObjectWriter.WriteStartObject when a root object instance was pre-supplied (via XamlObjectWriterSettings.RootObjectInstance) and the object writer reaches depth 1, but the root instance's type cannot be assigned to (does not implement/derive from) the XAML type of the root node in the node stream. The library refuses to substitute an incompatible root instance.","triggerScenarios":"Setting RootObjectInstance to an object whose CLR type cannot be assigned to the XamlType of the StartObject node being written at LiveDepth == 1, e.g. root instance is a Button while the stream declares a Window root.","commonSituations":"Pre-assigning a root instance in XamlObjectWriterSettings but loading XAML whose root element is a different type; refactoring XAML root elements without updating RootObjectInstance; plugin-style loading where the supplied instance type drifted from the serialized XAML.","solutions":["Make the RootObjectInstance type assignable to the XAML root type (implement the interface or derive from the declared root class).","Change the XAML's root element type so it matches (or is a base of) the supplied root instance's type.","Remove RootObjectInstance if the writer should instantiate the root itself from the node stream.","Verify with SchemaContext.GetXamlType(rootInstance.GetType()).CanAssignTo(rootNodeType) before invoking the load."],"exampleFix":"// before\nsettings.RootObjectInstance = new Button(); // XAML root is <Window ...>\nvar writer = new XamlObjectWriter(settings); // throws on WriteStartObject\n// after\nsettings.RootObjectInstance = new Window(); // assignable to declared root type\nvar writer = new XamlObjectWriter(settings);","handlingStrategy":"validation","validationCode":"var declared = schemaContext.GetXamlType(rootNodeType);\nif (!schemaContext.GetXamlType(settings.RootObjectInstance.GetType()).CanAssignTo(declared))\n    throw new InvalidOperationException(\"RootObjectInstance type not assignable to XAML root type.\");","typeGuard":"static bool RootAssignable(XamlSchemaContext sc, object rootInstance, XamlType rootType) =>\n    rootInstance == null || sc.GetXamlType(rootInstance.GetType())?.CanAssignTo(rootType) == true;","tryCatchPattern":"try { xamlServices.Load(writer); }\ncatch (XamlParseException ex) when (ex.Message.Contains(\"root\")) { RecreateWithoutRootInstance(); }","preventionTips":["Keep RootObjectInstance type in sync with the XAML root element.","Validate CanAssignTo before starting the load when pre-assigning root instances.","Update settings whenever the XAML root element type changes.","Prefer letting the writer instantiate the root unless substitution is required."],"tags":["xaml","parse-error","root-instance","type-assignment"],"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"}