Skip to content

Commit ad78fc3

Browse files
authored
Add code example for CA1002 rule (#48762) (#48763)
1 parent 699c913 commit ad78fc3

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

docs/fundamentals/code-analysis/quality-rules/ca1002.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ helpviewer_keywords:
1010
- DoNotExposeGenericLists
1111
author: gewarren
1212
ms.author: gewarren
13+
dev_langs:
14+
- CSharp
1315
---
1416
# CA1002: Do not expose generic lists
1517

@@ -45,6 +47,10 @@ By default, this rule only looks at externally visible types, but this is [confi
4547

4648
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.
4749

50+
## Example
51+
52+
:::code language="csharp" source="snippets/csharp/all-rules/ca1002.cs" id="snippet1":::
53+
4854
## When to suppress warnings
4955

5056
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.
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
using System.Collections.Generic;
2+
3+
namespace ca1001
4+
{
5+
//<snippet1>
6+
// This class violates the rule.
7+
public class MutableItems
8+
{
9+
// CA1002: Change 'List<string>' in 'MutableItems.Items' to
10+
// use 'Collection<T>', 'ReadOnlyCollection<T>' or 'KeyedCollection<K,V>'.
11+
public List<string> Items { get; } = new List<string>();
12+
13+
public void Add(string item)
14+
{
15+
Items.Add(item);
16+
}
17+
}
18+
19+
// This class satisfies the rule.
20+
public class ReadOnlyItems
21+
{
22+
private readonly List<string> _items = new List<string>();
23+
24+
public IReadOnlyCollection<string> Items => _items.AsReadOnly();
25+
26+
public void Add(string item)
27+
{
28+
_items.Add(item);
29+
}
30+
}
31+
//</snippet1>
32+
}

0 commit comments

Comments
 (0)