Synopsis: | Return interfaces to unchangeable collections |
Language: | C# |
Severity Level: | 5 |
Category: | Object lifecycle |
Description: |
In general, you don't want callers to be able to change an internal collection, so don't return arrays, lists or other collection classes directly. Instead, return an IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T> or IReadOnlyDictionary<T>. So public IEnumerable<FooBar> GetRecentItems() is preferred to public List<FooBar> GetRecentItems() Immutable collections such as ImmutableArray<T>, ImmutableList<T> and ImmutableDictionary<TKey, TValue> prevent modifications from the outside and are thus allowed. |
Literature References: |
Aviva AV1130 |