Skip to content

Latest commit

 

History

History
55 lines (43 loc) · 2.05 KB

File metadata and controls

55 lines (43 loc) · 2.05 KB

PH2129: Return immutable collections

Property Value
Package Philips.CodeAnalysis.MaintainabilityAnalyzers
Diagnostic ID PH2129
Category Maintainability
Analyzer ReturnImmutableCollectionsAnalyzer
CodeFix Yes
Severity Error
Enabled By Default Yes

Introduction

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<>

How to solve

Returned collection types from public methods should be either:

  1. IEnumerable
  2. one of the IReadOnly interfaces for these collections
  3. Immutable collections

The code fixer replaces the return type to the correct IReadOnly interface (option 2).

Example

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() {}
}

Configuration

This analyzer does not offer any special configuration. The general ways of suppressing diagnostics apply.