SBK0002: Mutation of a read-only JSON value

Analyzer SnowBank.Core
Severity Error
Code fix No

Message

'{0}' is read-only, and this call throws InvalidOperationException. Call ToMutable() to get an editable copy.

Why

A JsonObject or JsonArray built by JsonObject.ReadOnly.*, JsonArray.ReadOnly.*, ToReadOnly(), or Freeze() is immutable. An indexer assignment, or a call to Add, Set, Remove, Clear, Insert, or AddRange on it, throws InvalidOperationException every time the line runs.

The rule reports a local that is assigned once, by its declaration, from one of those sources, and later used as the receiver of such a mutation. A local assigned again after its declaration, a parameter, a field, or a direct receiver such as JsonObject.ReadOnly.Empty["a"] = 1 is not reported.

Bad

var frozen = JsonObject.ReadOnly.Create("Year", 1966);
frozen["Year"] = 1967; // throws InvalidOperationException

Good

var frozen = JsonObject.ReadOnly.Create("Year", 1966);
var draft = frozen.ToMutable();
draft["Year"] = 1967;
var updated = draft.ToReadOnly();

ToMutable() returns a mutable copy and leaves the read-only instance unchanged. Copy() also returns a mutable copy.

Suppress

#pragma warning disable SBK0002 // reason

or, for a whole project, in .editorconfig:

dotnet_diagnostic.SBK0002.severity = none