Rule C#:S3655 false positive for pattern

Language: C# 8 on .NET Framework 4.8

Rule: S3655 (reference is null on at least one execution path)

Scanners:

  • SonarScanner for .NET (MSBuild) version 5.10.0.59947
  • SonarLint for Visual Studio 2022 version 6.12.0.59751.

This code gives warning:

MyObject? myObject = GetObjectOrNull();
if (myObject is { SomeProperty: true })
{
    anotherObject.DoSomething(myObject.Value);
}

This results in the following message on myObject.Value (line 4):

S3655: ‘myObject’ is null on at least one execution path.

The given if-statement is equal to if (myObject != null && myobject.Value.SomeProperty), and the warning should not show.

Matching with pattern was introduced in C# 8, and using is { } checks if the variable contains reference to an object (not null).

Hi @Gakk,

Thank you for reporting this, I can confirm it’s a False Positive and created an issue for it here that you can track:

We plan to rework this rule in Q1 and that should also fix this issue.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.