{"record":{"id":"7007b6743de0d922","repo":"microsoft/autogen","slug":"cannot-convert-state-of-type-this-deserializedval","errorCode":null,"errorMessage":"Cannot convert state of type {this.deserializedValue.GetType()} to {typeof(T)}.","messagePattern":"Cannot convert state of type (.+?) to (.+?)\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"dotnet/src/Microsoft.AutoGen/AgentChat/State/SerializedState.cs","lineNumber":67,"sourceCode":"        this.jsonValue = JsonSerializer.SerializeToElement(this.deserializedValue, SerializerOptions);\n        return this.jsonValue.Value;\n    }\n\n    public static SerializedState Create<T>(T state) where T : notnull\n    {\n        return new SerializedState((object)state);\n    }\n\n    public T As<T>()\n    {\n        if (this.deserializedValue is T value)\n        {\n            return value;\n        }\n\n        if (this.deserializedValue != null)\n        {\n            throw new InvalidOperationException($\"Cannot convert state of type {this.deserializedValue.GetType()} to {typeof(T)}.\");\n        }\n\n        if (this.jsonValue == null)\n        {\n            throw new InvalidOperationException(\"State is not initialized.\");\n        }\n\n        T? result = JsonSerializer.Deserialize<T>(this.jsonValue!.Value, SerializerOptions)\n                    ?? throw new InvalidOperationException($\"Cannot deserialize state to {typeof(T)}.\");\n\n        this.deserializedValue = result;\n\n        return result;\n    }\n\n    private object? deserializedValue;\n    private JsonElement? jsonValue;\n","sourceCodeStart":49,"sourceCodeEnd":85,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/dotnet/src/Microsoft.AutoGen/AgentChat/State/SerializedState.cs#L49-L85","documentation":"SerializedState.As<T>() throws InvalidOperationException when the stored value's runtime type is not compatible with T. The method first tries a direct CLR cast (deserializedValue is T); if the stored object exists but the cast fails, this exception is thrown before any JSON round-trip is attempted — so this is a hard type mismatch, not a serialization problem.","triggerScenarios":"Calling As<string>() on state created via SerializedState.Create(new MyState()), or As<MyStateA>() when the checkpoint was saved from a different state type MyStateB. Any As<T> where T differs from the concrete type used at Create time.","commonSituations":"Changing the Team/Agent state class between development iterations while reusing old checkpoints; multiple agents sharing a state key with different expected types; copy-pasting LoadState/SaveState code between agents.","solutions":["Match T to the exact type used when the state was created/saved (inspect the checkpoint JSON to see the real shape).","If the underlying representation is JSON (jsonValue path), As<T> can deserialize — so for cross-type loading, load from the JSON representation rather than Create-typed objects.","Bump or clear persisted checkpoints after changing state types; add a state version field."],"exampleFix":"// before\nvar state = SerializedState.Create(new PlannerState { Plan = \"...\" });\nstring s = state.As<string>(); // throws: type is PlannerState, not string\n\n// after\nvar state = SerializedState.Create(new PlannerState { Plan = \"...\" });\nPlannerState s = state.As<PlannerState>();","handlingStrategy":"validation","validationCode":"// Before As<T>, confirm the stored representation can satisfy T:\n// if you control the writer, assert type equality at save time and record the type name alongside.\nif (savedTypeName != typeof(T).FullName) { /* load as JSON or re-create checkpoint */ }","typeGuard":null,"tryCatchPattern":"try { return state.As<T>(); }\ncatch (InvalidOperationException ex) when (ex.Message.StartsWith(\"Cannot convert state\"))\n{ /* type drift: migrate or fall back to default state */ }","preventionTips":["Record the state CLR type name in the checkpoint and compare before loading.","Clear/bump checkpoints whenever the state class shape changes."],"tags":["serialization","state","type-mismatch"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}