roslynator
roslynator copied to clipboard
Analyzer for limiting the usage of primary class constructor parameters
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
thisqualification 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);
}
}
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?
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.
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.