rspec/rules/S3887/rule.adoc

45 lines
1.8 KiB
Plaintext

== Why is this an issue?
Using the https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly[`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 https://learn.microsoft.com/en-us/dotnet/api/system.collections.immutable[immutable] or https://learn.microsoft.com/en-us/dotnet/api/system.collections.frozen[frozen] collection or remove the `readonly` modifier to clarify the behavior.
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
public class MyClass
{
public readonly string[] strings1; // Noncompliant
public readonly string[] strings2; // Noncompliant
public readonly string[] strings3; // Noncompliant
// ...
}
----
==== Compliant solution
[source,csharp,diff-id=1,diff-type=compliant]
----
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 - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly[readonly (C# Reference)]