csharpsquid:S1121 doesn't have exception for null-coalescing assignment operator

  • What language is this for?
    C#

  • Which rule?
    csharpsquid:S1121

  • Why do you believe it’s a false-positive/false-negative?
    I believe its a false positive because there is an exception for a very similar but older pattern that was the equivalent of ??= before ??= existed.

  • Using
    SonarQube Server Developer Edition v2025.3 (108892)

  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)

Below, the expression assigned to r1 will trigger S1121
However the expression assigned to r2 won’t, due to a clearly documented exception to the rule.

To my eye, the logic around cache in both expressions has the same intent, and the hunch would be the rule just hasn’t been updated to consider ??= in the same way?

 public (int,int) AnotherTest(int a)
 {
     List<int> cache = null;

     var r1 = a == 4 ? [] : cache ??= [1, 2, 3];

     var r2 = a == 3 ? [] : cache ?? (cache = [1, 2, 3]);

     return (r1.Count, r2.Count);
 }

Hello @mattr8750

I can confirm that null coalesce assignment causes false positives for S1121. This is a known issue already reported here: CS S1121 FP on async blocks and just parentheses as well

Hello,

we fixed the rule and do not raise on null coalesce assignment anymore. The fix will be part of the next release of the analyzer (It will be published here).

1 Like