dotnet / roslyn-analyzers

MIT License
1.55k stars 460 forks source link

Required Property has a default property set #7304

Open TonyValenti opened 2 months ago

TonyValenti commented 2 months ago

Describe the problem you are trying to solve

There is no point in setting a default value to a required property as the default must be overwritten.

This code should cause a new warning generated by the analyzer:

    public class A {
        public required string B { get; set; } = string.Empty; //Why?  We must overwrite this value on creation
    }

Describe suggestions on how to achieve the rule

See above

Additional context

None.

CollinAlpert commented 1 month ago

I'm not saying this analyzer would be a bad idea, however what you're saying is not completely true. It is possible not to overwrite the value:

class Program
{
    public static void Main()
    {
        A a = new A();
        Console.WriteLine(a.Value);
    }
}

class A
{
    public required string Value { get; set; } = "Hello";

    [SetsRequiredMembers]
    public A()
    {
    }
}

This prints Hello without any compiler errors or warnings.

TonyValenti commented 1 month ago

Good catch! The analyzer should also check for the presence of SetsRequiredMembers.