PrimaryConstructorParameterReassignment
Diagnostic Rule Overview
Field | Value |
---|---|
ID | SHIMMER2030 |
Analyzer title | Avoid reassigning primary constructor parameter |
Analyzer message | Primary constructor parameter '0' shouldn't be reassigned |
Code fix title | N/A |
Default severity | Hidden |
Minimum framework/language version | C# 12 |
Enabled by default? | No |
Category | ShimmeringStyle |
Link to code | PrimaryConstructorParameterReassignmentAnalyzer.cs |
Code fix exists? | No |
Detailed Explanation
Introduced in C# 12, primary constructors provide a concise syntax to declare constructors whose parameters are available anywhere in the body of the type. A primary constructor can almost allow you to remove all boilerplate fields that are created just to store the constructor parameters, except that a primary constructor parameter cannot be readonly
like a field can be. With this diagnostic enabled, you can assume that another method will not reassign the primary constructor parameter and therefore can treat it like a readonly
field and safely remove the boilerplate fields. One of the code fixes for IDE0290 (Use primary constructor (and remove fields)
) can help you with this.
Caveats:
- This diagnostic prevents reassignments, not mutations. For example, if you have a primary constructor parameter that's an array, you cannot prevent another method from updating the first element of the array.
- CS9105: Cannot use primary constructor parameter in this context prevents you from updating the primary constructor parameter in a regular constructor. If you do want to use the same thing throughout the class but want to do some preprocessing, either disable this diagnostic or rely on good old fields.
Examples
Flagged code:
namespace Tests;
class Test(int x)
{
void Do()
{
x = x / 2;
}
}
Justification of the Severity
This diagnostic prevents one of the valid use cases unlocked through primary constructors and therefore is disabled by default. See Create mutable state.
When to Suppress
Suppress this diagnostic if you want to maintain a mutable state using a primary constructor parameter, as mentioned above.