Code inspection: Captured primary constructor parameter is mutable
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.
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();
}
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();
}
Last modified: 07 August 2024