Code inspection: Captured primary constructor parameter is mutable
Category: Potential Code Quality Issues
ID: CapturedPrimaryConstructorParameterIsMutable
EditorConfig: resharper_captured_primary_constructor_parameter_is_mutable_highlighting=[error|warning|suggestion|hint|none]
Language: C#
Requires SWA: No
tip
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 cases when "captured" primary constructor parameters are actually modified by the members.
A quick-fix helps explicitly express the mutable class-level state by introducing an ordinary mutable field.
Suboptimal code
class Service(IDependency dependency){ public void DoWork() => dependency.Use(); public void SetupHack() { dependency = new AdhocDependencyImpl(); // Warning DoWork(); }}interface IDependency{ void Use();}class AdhocDependencyImpl : IDependency{ public void Use() => throw new NotImplementedException();}
After the quick-fix
class Service(IDependency dependency){ private IDependency _dependency = dependency; public void DoWork() => _dependency.Use(); public void SetupHack() { _dependency = new AdhocDependencyImpl(); DoWork(); }}interface IDependency{ void Use();}class AdhocDependencyImpl : IDependency{ public void Use() => throw new NotImplementedException();}