Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/fundamentals/code-analysis/quality-rules/ca1002.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ helpviewer_keywords:
- DoNotExposeGenericLists
author: gewarren
ms.author: gewarren
dev_langs:
- CSharp
---
# CA1002: Do not expose generic lists

Expand Down Expand Up @@ -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 <xref:System.Collections.Generic.List%601?displayProperty=fullName> 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.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System.Collections.Generic;

namespace ca1001
{
//<snippet1>
// This class violates the rule.
public class MutableItems
{
// CA1002: Change 'List<string>' in 'MutableItems.Items' to use 'Collection<T>', 'ReadOnlyCollection<T>' or 'KeyedCollection<K,V>'
public List<string> Items { get; } = new List<string>();

public void Add(string item)
{
Items.Add(item);
}
}

// This class satisfies the rule.
public class ReadOnlyItems
{
private readonly List<string> _items = new List<string>();

public IReadOnlyCollection<string> Items => _items.AsReadOnly();

public void Add(string item)
{
_items.Add(item);
}
}
//</snippet1>
}