SBK1003: Null test on a JSON value
| Analyzer | SnowBank.Core |
| Severity | Warning (correctness) |
| Code fix | Yes |
Message
A JsonValue is never a null reference: a missing member reads as JsonNull.Missing. Test it with IsNullOrMissing().
Why
The indexers and Get* methods of JsonObject and JsonArray return JsonNull.Missing for a missing member and JsonNull.Null for an explicit null. They never return a null reference, so value == null is always false and the code after it runs for missing members too.
The rule applies to a value read from a JSON value (an indexer, a method of a JSON type, or a local initialized with one), where the nullable context is enabled and the value is declared non-nullable. Any other JsonValue is not reported: a parameter, a field, a property, or the result of another method can hold null whatever its annotation says, so a null test on it is a legitimate guard. A JsonValue? that your own code can set to null is not reported either.
Bad
if (obj["name"] == null)
{
return "anonymous";
}
Good
if (obj["name"].IsNullOrMissing())
{
return "anonymous";
}
IsMissing() tests only for a missing member, and IsNull only for an explicit null.
Code fix
The fix rewrites x == null and x is null to x.IsNullOrMissing(), and x != null and x is not null to !x.IsNullOrMissing(). The x ?? y and x?. forms are reported without a fix.
Suppress
#pragma warning disable SBK1003 // reason
or, for a whole project, in .editorconfig:
dotnet_diagnostic.SBK1003.severity = none