Skip to content

Commit c8a1156

Browse files
committed
Add code example for CA1030 rule (#48914)
1 parent 4dd6d45 commit c8a1156

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ helpviewer_keywords:
1010
- UseEventsWhereAppropriate
1111
author: gewarren
1212
ms.author: gewarren
13+
dev_langs:
14+
- CSharp
1315
---
1416
# CA1030: Use events where appropriate
1517

@@ -42,6 +44,10 @@ Some common examples of events are found in user interface applications where a
4244

4345
If the method is called when the state of an object changes, consider changing the design to use the .NET event model.
4446

47+
## Example
48+
49+
:::code language="csharp" source="snippets/csharp/all-rules/ca1030.cs" id="snippet1":::
50+
4551
## When to suppress warnings
4652

4753
Suppress a warning from this rule if the method does not work with the .NET event model.
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
using System.Collections.Generic;
2+
3+
namespace ca1030
4+
{
5+
//<snippet1>
6+
// This class violates the rule.
7+
public class BadButton
8+
{
9+
private readonly List<Action> _clickHandlers = new List<Action>();
10+
11+
public void AddOnClick(Action handler)
12+
{
13+
// Some internal logic...
14+
15+
_clickHandlers.Add(handler);
16+
}
17+
18+
public void RemoveOnClick(Action handler)
19+
{
20+
// Some internal logic...
21+
22+
_clickHandlers.Remove(handler);
23+
}
24+
25+
public void FireClick()
26+
{
27+
foreach (Action handler in _clickHandlers)
28+
{
29+
handler();
30+
}
31+
}
32+
}
33+
34+
// This class satisfies the rule.
35+
public class GoodButton
36+
{
37+
private EventHandler? _clickHandler;
38+
39+
public event EventHandler? ClickHandler
40+
{
41+
add
42+
{
43+
// Some internal logic...
44+
45+
_clickHandler += value;
46+
}
47+
remove
48+
{
49+
// Some internal logic...
50+
51+
_clickHandler -= value;
52+
}
53+
}
54+
55+
protected virtual void OnClick(EventArgs e)
56+
{
57+
_clickHandler?.Invoke(this, e);
58+
}
59+
60+
public void Click()
61+
{
62+
OnClick(EventArgs.Empty);
63+
}
64+
}
65+
//</snippet1>
66+
}

0 commit comments

Comments
 (0)