Skip to main content

PrimaryConstructorParameterReassignment

Diagnostic Rule Overview

FieldValue
IDSHIMMER2030
Analyzer titleAvoid reassigning primary constructor parameter
Analyzer messagePrimary constructor parameter '0' shouldn't be reassigned
Code fix titleN/A
Default severityHidden
Minimum framework/language versionC# 12
Enabled by default?No
CategoryShimmeringStyle
Link to codePrimaryConstructorParameterReassignmentAnalyzer.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:

  1. 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.
  2. 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.