JetBrains Rider 2024.3 Help

Code inspection: Primary constructor parameter capturing is disallowed

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.

public class Sample(int parameter) { public int PropertyCapture => parameter; }
public class Sample(int parameter) { private readonly int _parameter = parameter; public int PropertyCapture => _parameter; }
Last modified: 07 August 2024