A variable is dereferenced in the branch where it was just tested to be null
What it finds
In if (x == null) { x.Close(); } the branch runs only when x is null, so the member access throws NullReferenceException every time. Usually the test is inverted, or the branch was meant to use another variable. The rule follows the branch in order and stops at the first assignment to the variable; it reports a member or element access on it before that. Accesses inside lambdas and nameof are left alone.
From the rule's source, null_dereferenced_when_null.rs.
class Files{ void Close(Stream s, Stream t) { if (s == null) { s.Dispose();tx0 reports: s is null here, so this access throws } if (t != null) { t.Flush(); } if (s == null) { Log(s != null && s.Ready); } else { t = Open(); t.Flush(); } } Stream Open() => null; void Log(bool b) { }} class Stream{ public void Dispose() { } public void Flush() { } public bool Ready => true;} Turn it on, off or suppress it
The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:
[rules]
"tx0/csharp:null-dereferenced-when-null" = "off"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/csharp:null-dereferenced-when-null] reason="..."tx0 explain tx0/csharp:null-dereferenced-when-null shows the same in the terminal. Found a false positive? Report it.