CSharp: False Positive: Null reference bug and Null coalescing in an if/return statement

It has been observed that there is false positive null reference bug where an object assumed null given a NOT operator and Null Coalescing in an if/return statement.

How to Reproduce

if ( !object?.Collections?.Any( ) ?? true )
{
  // If 'object' or 'Collections' is null or empty, quit.
  return true;
}

//Assumes Null Reference Exception is thrown on 'object' when accessing 'Collections' property.
foreach( var element in object.Collections )
{
  // Run Action
}
return true;

If object is null, the if condition should be true and invoke the return statement. The NOT operator is not invoked because object as null forces the condition to invoke null coalescing handler and set as true.
On the other hand, the NOT operator is also not wrapping with the null coalescing handler.
Consider when object is not null and collections have elements:

The condition should be true

!object?.Collections?.Any( ) ?? true

Versus a wrapping parenthesis, the condition should be false

!(object?.Collections?.Any( ) ?? true)

Workaround
Split and update the if statement to be more readable

if ( object?.Collections == null || !object.Collections.Any( ) )
{
  return true;
}

Example:
testnull2.zip (235.1 KB)

Hey there.

Thanks for the report.

I believe this bug is tracked at S2259 FP: Null conditional combined with null coalescing · Issue #4537 · SonarSource/sonar-dotnet · GitHub, the fix merged into master and a release coming rather soon.

1 Like