SonarSource / sonar-dotnet

Code analyzer for C# and VB.NET projects
https://redirect.sonarsource.com/plugins/csharp.html
GNU Lesser General Public License v3.0
797 stars 229 forks source link

Fix S3963: False-positive for initializing static field in static ctor that is present due to other reasons #9656

Open witoldkaras opened 2 months ago

witoldkaras commented 2 months ago

Description

S3963 is fired when static field initialization is present in static constructor that contains also other code warranting its existence. Inline initialization of those fields doesn't change anything regarding static constructor presence, thus making the change pointless in such case.

Repro steps

    internal static class S3963Test
    {
        private static readonly string Foo;
        private static readonly string Bar;
        private static readonly string Baz;

        static S3963Test()
        {
            (Foo, Bar) = GetFooBar();
            Baz = GetBaz();    // triggers S3963 despite static ctor being necessary anyways due to line above (which by itself doesn't trigger the rule)
        }

        private static (string, string) GetFooBar()
        {
            return ("Foo", "Bar");
        }

        private static string GetBaz()
        {
            return "Baz";
        }
    }

Expected behavior

Do not fire S3963 when static field initialization is not the only thing warranting existence of static ctor.

Actual behavior

S3963 is fired

Known workarounds

Suppress S3963.

Related information

SonarAnalyzer.CSharp 9.32.0.97167

zsolt-kolbay-sonarsource commented 2 months ago

Thank you for reporting the issue. Confirmed as False Positive.