JetBrains Rider
 
Get JetBrains Rider
Get your hands on the new features ahead of the release by joining the Early Access Program for Rider 2025.1! Learn more

Code inspection: Primary constructor parameter capturing is disallowed

Last modified: 07 August 2024

Primary constructors for non-record types make your type definitions more compact. However, as a downside, they introduce a potential problem of "capturing" primary constructor parameters inside instance member bodies. All parameter variables in C# are mutable, which means that any instance member can change its value after the initialization, and there is no syntax to enforce the parameter to be readonly.

This inspection reports all primary constructor parameters "captured" by instance members, even if there is currently no code that modifies the captured parameters. This approach might be too strict; therefore, this inspection is disabled by default. You can enable it to disallow the capturing of primary constructor parameters.

A quick-fix helps explicitly express the mutable class-level state by introducing an ordinary mutable field.