diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1002.md b/docs/fundamentals/code-analysis/quality-rules/ca1002.md index e7ab8e82def88..2cbd1731aa77d 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1002.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1002.md @@ -10,6 +10,8 @@ helpviewer_keywords: - DoNotExposeGenericLists author: gewarren ms.author: gewarren +dev_langs: + - CSharp --- # CA1002: Do not expose generic lists @@ -45,6 +47,10 @@ By default, this rule only looks at externally visible types, but this is [confi To fix a violation of this rule, change the type to one of the generic collections that's designed for inheritance. +## Example + +:::code language="csharp" source="snippets/csharp/all-rules/ca1002.cs" id="snippet1"::: + ## When to suppress warnings Do not suppress a warning from this rule unless the assembly that raises this warning is not meant to be a reusable library. For example, it would be safe to suppress this warning in a performance-tuned application where a performance benefit was gained from the use of generic lists. diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1002.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1002.cs new file mode 100644 index 0000000000000..3440b130d48c3 --- /dev/null +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1002.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; + +namespace ca1001 +{ + // + // This class violates the rule. + public class MutableItems + { + // CA1002: Change 'List' in 'MutableItems.Items' to + // use 'Collection', 'ReadOnlyCollection' or 'KeyedCollection'. + public List Items { get; } = new List(); + + public void Add(string item) + { + Items.Add(item); + } + } + + // This class satisfies the rule. + public class ReadOnlyItems + { + private readonly List _items = new List(); + + public IReadOnlyCollection Items => _items.AsReadOnly(); + + public void Add(string item) + { + _items.Add(item); + } + } + // +}