roslynator icon indicating copy to clipboard operation
roslynator copied to clipboard

Analyzer for limiting the usage of primary class constructor parameters

Open glen-84 opened this issue 1 year ago • 3 comments
trafficstars

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);
    }
}

glen-84 avatar Nov 25 '23 08:11 glen-84

They cannot be made read-only.

The backing field is read-only.

https://sharplab.io/#v2:EYLgZgpghgLgrgJwgZwLQAUEEsC2UECeAwgPYB2yMCcAxjCQsgDQAmIA1AD4ACAzAATJoAGwgt+3AEz8AogA8oOAA6iAFNwCMABn4QFy0QEoAsACgA3mf7X+S7ADdYEfkigtywghO279K5wC8vor+ANxmAL5AA==

Or did you mean something else?

josefpihrt avatar Nov 25 '23 14:11 josefpihrt

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.

glen-84 avatar Nov 25 '23 18:11 glen-84

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.

pfeigl avatar Feb 26 '24 15:02 pfeigl