Why do you believe it’s a false-positive/false-negative?
The if condition compares the result of a conditional expression with a trinary type (bool?) to the value true which logically excludes the possibility of entering the conditional block with a null value.
Are you using…
SonarCloud
How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)
namespace Reproduce
{
public static class Extensions {
public static string DomainPart(this string realm, string root) {
if (string.IsNullOrEmpty(root)) throw new ArgumentException("Root domain may not be null or empty.", nameof(root));
if (realm?.EndsWith($".{root}") == true) {
var subdomain = realm.Substring(0, realm.Length - root.Length - 1); // <- S2259 twice here
var parts = subdomain.Split(".");
return parts.Length switch {
0 => null,
1 => realm,
2 => realm.Substring(parts[0].Length + 1), // parts[0] could be null here.
_ => null
};
} else return null;
}
}
}
I have reproduced the issue you describe, but only on an older version of our C# Analyzer (9.1).
A fix for this False Positive has been released in version 9.2.
The minimal reproducer is the following:
public static class Repro_S2259
{
public static void DomainPart1(string realm)
{
if (realm?.EndsWith($".") == true)
{
realm.Substring(0, 1); // <- S2259
}
}
}
Currently, SonarCloud runs version 9.4 of the C# Analyzer, and the issue is not reproducible for me, neither on .NET Core nor on .NET Framework.
If your test was made several weeks ago before 9.2 was included in SonarCloud, I would suggest you try running the analysis again. Both False Positive cases on line var subdomain = realm.Substring(0, realm.Length - root.Length - 1); should disappear.
If you can still reproduce the issue on the current version of SonarCloud, could you please report:
the version of .NET your project is using
whether nullable reference types are activated for the project
After an internal discussion on your issue, we think you may have a caching issue.
In order to validate our assumptions, and better understand where the potential caching issue may be, we would appreciate it if you could:
first try rerunning the analysis, as suggested in the comment above
if you can still reproduce the issue, try deleting the following folder on the machine running the scanner: %Temp%\.sonarqube, then re-run the analysis
if you can still reproduce the issue, try deleting the following folder on the machine running the scanner: %UserProfile%\.sonar\cache, then re-run the analysis
let us know if the issue disappears after step 1, 2, or 3, or does not disappear at all.