Skip to content

Commit 5d55688

Browse files
authored
Add code example for CA1030 rule (#48914) (#48915)
1 parent 7957045 commit 5d55688

File tree

2 files changed

+73
-0
lines changed

2 files changed

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

0 commit comments

Comments
 (0)