C#: False positive variable is null on at least one execution path

I have a piece of code that looks like this:

public int Compare(... left, ... right)
{
  string leftName = ...;
  string rightName = ...;
  if (string.Equals(leftName, rightName))
    return 0;

  if (leftName == null)
  {
    ERROR: 'rightName' is null on at least one execution path.
    if (rightName.EndsWith("module.js"))

To me we are in one of two cases here:

  1. SonarQube simply doesn’t know, but then it shouldn’t report it with the wording it does, instead it should be a warning with “rightName may be null”…
  2. SonarQube think it knows that rightName can be null but actually gets that completely wrong.

IF leftName is null in this block, rightName cannot be null, otherwise the “string.Equals” would have returned from the method, hence we KNOW that rightName holds a value in this context.

(This is even verified with a Unit test)

hi @jeme, welcome to our community!

I tried to reproduce with the latest SonarCsharp analyzer and could not. This is my reproducer attempt:

    class TestCommunityFP
    {
        public int Compare(string leftName, string rightName)
        {
            if (string.Equals(leftName, rightName))
                return 0;

            if (leftName == null)
            {
                if (rightName.EndsWith("module.js")) // ok
                {
                    return 1;
                }
            }
            return 0;
        }
    }

If you ignored such a case previously, can you dig it out again?, otherwise I am not sure I can get to verify it in our code base any time soon :(.

Will try though if there is no easier option.

I tried to reproduce it with SonarCSharp 7.15 and 8.0 and I could not. If you’re on a really old analyzer version, please update.

What version of SonarQube are you on?
What version of the SonarCSharp plugin are you using?

I am using the scanner from here: https://docs.sonarqube.org/latest/analysis/scan/sonarscanner-for-msbuild/

After your response here I updated from:

  • sonar-scanner-msbuild-4.6.0.1930-net46.zip
    to
  • sonar-scanner-msbuild-4.7.1.2311-net46.zip
    (The latest one I could find under that link)

But As i stated, I did ignore it previously, so wouldn’t I have to somehow “Unignore” it for it to pop up again (if it does)?

The scanner downloads the plugin (which is used to analyze the code) from your SonarQube instance. The plugin version can be checked either in the scanning logs for the Begin step, or in your SonarQube instance.

What do you mean you ignored it? Did you mark it as FP or Won't fix in SQ, and now it appears again as a fresh problem?