Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Required Property has a default property set #7304

Open
TonyValenti opened this issue Apr 25, 2024 · 2 comments
Open

Required Property has a default property set #7304

TonyValenti opened this issue Apr 25, 2024 · 2 comments

Comments

@TonyValenti
Copy link

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
Copy link
Contributor

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants