rspec/rules/S2384/csharp/rule.adoc

54 lines
1.7 KiB
Plaintext
Raw Normal View History

2021-01-27 13:42:22 +01:00
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.
2020-06-30 12:48:07 +02:00
2021-01-27 13:42:22 +01:00
Instead use and store a copy of the mutable collection, or return an immutable collection wrapper, e.g. ``++System.Collections.ObjectModel.ReadOnlyCollection<T>++``.
2020-06-30 12:48:07 +02:00
2021-01-27 13:42:22 +01:00
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.
2020-06-30 12:48:07 +02:00
This rule checks that mutable collections are not stored or returned directly.
== Noncompliant Code Example
----
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
----
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[]