rspec/rules/S2384/csharp/rule.adoc
2022-02-04 16:28:24 +00:00

74 lines
2.0 KiB
Plaintext

Mutable collections are those whose state can be changed. For instance, ``++Array++`` and ``++List<T>++`` are mutable, but ``++System.Collections.ObjectModel.ReadOnlyCollection<T>++`` and ``++System.Collections.Immutable.ImmutableList<T>++`` are not. Mutable collection class members should not be returned to a caller or accepted and stored directly. Doing so leaves you vulnerable to unexpected changes in your class state.
Instead use and store a copy of the mutable collection, or return an immutable collection wrapper, e.g. ``++System.Collections.ObjectModel.ReadOnlyCollection<T>++``.
Note that you can't just return your mutable collection through the ``++IEnumerable<T>++`` interface because the caller of your method/property could cast it down to the mutable type and then change it.
This rule checks that mutable collections are not stored or returned directly.
== Noncompliant Code Example
[source,csharp]
----
class A
{
private List<string> names = new List<string>();
public ICollection<string> Names => names; // Noncompliant
public IEnumerable<string> GetNames() // Noncompliant
{
return names;
}
public void SetNames(List<string> strings)
{
this.names = strings; // Noncompliant
}
}
----
== Compliant Solution
[source,csharp]
----
class A
{
private List<string> names = new List<string>();
private ReadOnlyCollection<string> readOnlyNames = new ReadOnlyCollection<string>(names);
public ICollection<string> Names => readOnlyNames; // Return a collection wrapper
public IEnumerable<string> GetNames()
{
names.ToList(); // Make a copy
}
public void SetNames(List<string> strings)
{
this.names.Clear();
this.names.AddRange(strings); // Make a copy
}
}
----
include::../see.adoc[]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]