S2259 False Positive "Null pointers should not be dereferenced"

  • SonarLint version
  • Visual Studio 2019
  • C# code targeting .NET Core 3.1.

The warning is triggered on a line immediately after the necessary null checks have already been performed. This is likely due to the tool not seeing a direct case where I check that the variable is not null, even though the preceding combined null checks all overlap to cover that case. I have attached a minimal project that shows this behavior.

SonarLint S2259 False Positive Replication VS 2019 Solution.zip (15.1 KB)

Thanks for providing a complete solution. I’ve copied the .cs code here for simplicity.

namespace SonarLint_S2259_False_Positive_Replication
	public class FPReplication
		public int PartialChecksForSemanticVersionComparison(string PreRelease, string OtherPreRelease)
			if (PreRelease == OtherPreRelease) { return 0; }
			if (PreRelease != null && OtherPreRelease == null) { return -1; }
			if (PreRelease == null && OtherPreRelease != null) { return 1; }

			_ = PreRelease.Split('.'); //S2259 false positive on this line, where it doesn't see that lines 9 and 11 overlap to protect against System.NullReferenceException
			_ = OtherPreRelease.Split('.');

			return 0;

Short correction here. I called out the line numbers 9 and 11, but deleted an unused using section a the top of the file right before saving and zipping up the project. I’m meaning to point out the first and third if statements on lines 7 and 9.

Interestingly, only the first split call seems to trigger S2259. I just noticed that the second call is covered by the same checks but doesn’t trigger the warning.

Hello @marshall

Thank you for reporting this. We will add this case to our test suite here FP S2259: Reproducer: Null check with two variables by martin-strecker-sonarsource · Pull Request #6025 · SonarSource/sonar-dotnet · GitHub
We are working on that rule at the moment and your case should be covered in one of the next releases.

Best, Martin

Excellent, thanks!

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