DotNetAnalyzers / StyleCopAnalyzers

An implementation of StyleCop rules using the .NET Compiler Platform
MIT License
2.61k stars 506 forks source link

Extend SA1129 to cover parameterless struct constructors #3854

Closed Arthri closed 1 month ago

Arthri commented 1 month ago

C#10 introduced the ability to declare and use parameterless struct constructors, which means new Struct() and default(Struct) can be different. Consider the following code sample,

using System;

X.L(); // 12
X.K(); // 0

internal struct X
{
    public int I;

    public X()
    {
        I = 12;
    }

    public static void L()
    {
        Console.WriteLine(new X().I);
    }

    public static void K()
    {
        Console.WriteLine(default(X).I);
    }
}

I believe that SA1129 "A value type was constructed using the syntax new T()." should not be removed, rather, it should check whether the struct defines a parameterless constructor before raising any warnings

bjornhellander commented 1 month ago

Duplicate of #3430