org.sonar.plugins.csharp.S3887.html Maven / Gradle / Ivy
Why is this an issue?
Using the readonly
keyword on a
field means it can’t be changed after initialization. However, that’s only partly true when applied to collections or arrays. The
readonly
keyword enforces that another instance can’t be assigned to the field, but it cannot keep the contents from being updated. In
practice, the field value can be changed, and the use of readonly
on such a field is misleading, and you’re likely not getting the
behavior you expect.
This rule raises an issue when a non-private, readonly
field is an array or collection.
How to fix it
To fix this, you should either use an immutable or frozen collection or remove the readonly
modifier to
clarify the behavior.
Code examples
Noncompliant code example
public class MyClass
{
public readonly string[] strings1; // Noncompliant
public readonly string[] strings2; // Noncompliant
public readonly string[] strings3; // Noncompliant
// ...
}
Compliant solution
public class MyClass
{
public string[] strings1; // Compliant: remove readonly modifier
public readonly ImmutableArray<string> strings; // Compliant: use an Immutable collection
private readonly string[] strings; // Compliant: reduced accessibility to private
// ...
}
Resources
Documentation
- Microsoft Learn - readonly (C# Reference)
© 2015 - 2024 Weber Informatics LLC | Privacy Policy