csharp:S1125 FP comparing nullable bool to bool literal

  • What language is this for? C#
  • Which rule? S1125
  • Why do you believe it’s a false-positive/false-negative? Comparing a value of type bool? to a boolean literal using == or != does not make the boolean literal redundant, since the value can be true, false or null. I like x == true better than x ?? false since it’s more direct and has a better precedence (x == true && y needs no parentheses while (x ?? false) && y needs them).
  • Are you using
    • SonarQube Cloud? yes
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)
Console.WriteLine(CreateX(null).Foo);

static X CreateX(bool? value) {
    X result = new() {
        Foo = value == false ? true : null // wrong S1125
    };
    return result;
}

sealed class X {
    public bool? Foo;
}

This is a regression, probably either because of a change on SonarCloud around 2026-03-11 or because I upgraded the C# version from 12.0 to 14.0. (I’m sorry, I have not tested this theory.)

I liked the previous S1125 because it enforced there was only == true or == false for nullable booleans.

I temporarily reverted the C# version to 12.0 and that did not help.

Hi @jilles-sg,

We were unable to reproduce this with the current analyzer. Comparisons of bool? to a boolean literal using == or != have been treated as compliant since SonarAnalyzer.CSharp 8.34 (released January 17, 2022), including the exact pattern you described (value == false ? true : null in a ternary expression). That fix was introduced in sonar-dotnet#5219 / PR #5220.

Could you share the full flagged code? There may be a subtlety in the context we haven’t accounted for.

Thanks for the clear reproducer!

1 Like