sonar-dotnet icon indicating copy to clipboard operation
sonar-dotnet copied to clipboard

Fix S3257 FN: collection expressions

Open antonioaversa opened this issue 1 year ago • 0 comments

New C# 12 collection expressions allow to make collection initialization even shorter than it used to be with Implicitly typed arrays.

    void ExplicitTypeDeclaration()
    {
        int[] a1 = [1, 2, 3];         // Compliant
        a1 = [1, 2, 3];               // Compliant, reassignment
        int[] a2 = new[] { 1, 2, 3 }; // FN, can be written as [1, 2, 3]
        a2 = new[] { 1, 2, 3 };       // FN, can be written as [1, 2, 3], reassignment
    }

Notice that the rule may require reworking, since:

  • var a = [ 1, 2, 3 ] is not valid, so we need to ensure that reduction from new[] { ... } to [ ... ] doesn't generate invalid code
  • var a = /*type inferred int[]*/; a = []; produces a compilation error
  • there is also an overlapping with IDE0300

See here for more details.

antonioaversa avatar Sep 29 '23 15:09 antonioaversa