Skip to content

Commit 2e717d6

Browse files
committed
Add code example for CA1002 rule (#48762)
1 parent 0fbbf03 commit 2e717d6

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ By default, this rule only looks at externally visible types, but this is [confi
4545

4646
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.
4747

48+
## Example
49+
:::code language="csharp" source="snippets/csharp/all-rules/ca1002.cs" id="snippet1":::
50+
4851
## When to suppress warnings
4952

5053
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: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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 'ViolationItems.Members' to use 'Collection<T>', 'ReadOnlyCollection<T>' or 'KeyedCollection<K,V>'
10+
public List<string> Items { get; } = new List<string>();
11+
12+
public void Add(string item)
13+
{
14+
Items.Add(item);
15+
}
16+
}
17+
18+
// This class satisfies the rule.
19+
public class ReadOnlyItems
20+
{
21+
private readonly List<string> _items = new List<string>();
22+
23+
public IReadOnlyCollection<string> Items => _items.AsReadOnly();
24+
25+
public void Add(string item)
26+
{
27+
_items.Add(item);
28+
}
29+
}
30+
//</snippet1>
31+
}

0 commit comments

Comments
 (0)