| Property | Value |
|---|---|
| Package | Philips.CodeAnalysis.MaintainabilityAnalyzers |
| Diagnostic ID | PH2129 |
| Category | Maintainability |
| Analyzer | ReturnImmutableCollectionsAnalyzer |
| CodeFix | Yes |
| Severity | Error |
| Enabled By Default | Yes |
Returned objects from public methods should be protected against mutation from outside your class. Therefore, return only immutable or readonly collections from a public method, otherwise these collections can be changed by the caller without your code noticing.
The list of mutable collections that are checked are:
System.Collections.Generic.List<>System.Collections.Generic.Queue<>System.Collections.Generic.SortedList<>System.Collections.Generic.Stack<>System.Collections.Generic.Dictionary<>System.Collections.Generic.IList<>System.Collections.Generic.IDictionary<>
Returned collection types from public methods should be either:
IEnumerable- one of the
IReadOnlyinterfaces for these collections - Immutable collections
The code fixer replaces the return type to the correct IReadOnly interface (option 2).
Code that triggers a diagnostic:
using System.Collections.Generic;
public class BadExample {
public List<string> GetList() {}
}And the replacement code:
using System.Collections.Generic;
public class GoodExample {
public IReadOnlyList<string> GetList() {}
}This analyzer does not offer any special configuration. The general ways of suppressing diagnostics apply.