Collection properties should be read only
Collection properties should be read only
Microsoft docsDescription
A writable collection property lets users replace the collection with a completely different collection. A read-only or init-only property prevents the collection from being replaced, but still allows individual members to be set. If replacing the collection is a goal, the preferred design pattern is to include a method to remove all elements from the collection, and a method to repopulate the collection. See the System.Collections.ArrayList.Clear and System.Collections.ArrayList.AddRange methods of the System.Collections.ArrayList class for an example of this pattern.
Both binary and XML serialization support read-only properties that are collections. The System.Xml.Serialization.XmlSerializer class has specific requirements for types that implement System.Collections.ICollection and System.Collections.IEnumerable to be serializable.
Cause
An externally visible, writable property is of a type that implements System.Collections.ICollection. This rule ignores arrays, indexers (properties with the name 'Item'), immutable collections, readonly collections, and permission sets.
How to fix violations
Use one of the following approaches to fix a violation of this rule:
- Make the property read-only or init-only. A read-only or init-only property prevents the collection from being replaced while still allowing individual members to be set. If the design requires replacing the collection's contents, add methods to clear and repopulate the collection. For an example of this pattern, see the System.Collections.ArrayList.Clear and System.Collections.ArrayList.AddRange methods.
- Change the property type to a read-only collection type. If callers don't need to modify the collection, change the property type to a read-only collection, such as System.Collections.ObjectModel.ReadOnlyCollection`1. This approach makes the read-only intent explicit in the type signature.
- Change the property type to a thread-safe concurrent collection type, while keeping the property read-only. If the design requires multiple threads to modify the collection concurrently, expose a read-only property (no setter) whose type is a concurrent collection, such as System.Collections.Concurrent.ConcurrentBag`1. CA2227 is triggered by a writable collection property, not by the collection type, so the property must still be read-only. The concurrent collection choice only addresses thread-safe mutation of the returned collection instance.
Example
#pragma warning disable CA2227
// The code that's violating the rule is on this line.
#pragma warning restore CA2227When to suppress
You can suppress the warning if the property is part of a Data Transfer Object (DTO)) class.
Otherwise, don't suppress warnings from this rule.