== Why is this an issue? Mutable collections are those whose state can be changed. For instance, ``++Array++`` and ``++List++`` are mutable, but ``++System.Collections.ObjectModel.ReadOnlyCollection++`` and ``++System.Collections.Immutable.ImmutableList++`` 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++``. Note that you can't just return your mutable collection through the ``++IEnumerable++`` 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 names = new List(); public ICollection Names => names; // Noncompliant public IEnumerable GetNames() // Noncompliant { return names; } public void SetNames(List strings) { this.names = strings; // Noncompliant } } ---- === Compliant solution [source,csharp] ---- class A { private List names = new List(); private ReadOnlyCollection readOnlyNames = new ReadOnlyCollection(names); public ICollection Names => readOnlyNames; // Return a collection wrapper public IEnumerable GetNames() { names.ToList(); // Make a copy } public void SetNames(List strings) { this.names.Clear(); this.names.AddRange(strings); // Make a copy } } ---- == Resources * CWE - https://cwe.mitre.org/data/definitions/374[CWE-374 - Passing Mutable Objects to an Untrusted Method] * CWE - https://cwe.mitre.org/data/definitions/375[CWE-375 - Returning a Mutable Object to an Untrusted Caller] ifdef::env-github,rspecator-view[] ''' == Implementation Specification (visible only on this page) include::../message.adoc[] ''' == Comments And Links (visible only on this page) === on 15 Mar 2017, 16:13:35 Amaury Levé wrote: \[~ann.campbell.2] I changed a bit this rule to focus only on collections for C# as ``++Date++`` is immutable for us. === on 15 Mar 2017, 18:47:09 Ann Campbell wrote: Works for me [~amaury.leve] include::../comments-and-links.adoc[] endif::env-github,rspecator-view[]