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

Analyzer for limiting the usage of primary class constructor parameters #1286

Open
glen-84 opened this issue Nov 25, 2023 · 3 comments
Open

Comments

@glen-84
Copy link
Contributor

glen-84 commented Nov 25, 2023

Allow primary class constructor parameters to only be used to initialize fields/properties, and not inside methods.

Since:

  • They cannot be made read-only.
  • It's not ideal for them to be used without this qualification everywhere within the class body.

Okay:

public sealed class Example(string example)
{
    private readonly string example = example;

    public void Method()
    {
        Console.WriteLine(this.example);
    }
}

Not okay:

public sealed class Example(string example)
{
    public void Method()
    {
        Console.WriteLine(example);
    }
}
@josefpihrt
Copy link
Collaborator

@glen-84
Copy link
Contributor Author

glen-84 commented Nov 25, 2023

That's the "okay" code, when you assign the parameter to a read-only field.

This is the "not okay" code:

https://sharplab.io/#v2:EYLgZgpghgLgrgJwgZwLQAUEEsC2UECeAwgPYB2yMCcAxjCQsgDQAmIA1AD4ACATAIwBYAFAjuAZgAEyaABsILSX0kBRAB5QcAB3kAKbvwAMkiBu3yAlCIDeIyfaVTuAFkkBZCDAAWJFrqvCDpK2gUEOBgCcuqaaOhAWANx2DgC+IilAA===

... where the parameter (example) is mutable, and available anywhere within the class without qualification.

@pfeigl
Copy link

pfeigl commented Feb 26, 2024

I'd actually like to be able to use primary constructor arguments in my whole class and would favor a rule telling me to handle them as read-only.

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

No branches or pull requests

3 participants