Skip to content
Open
Show file tree
Hide file tree
Changes from all 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/ca1030.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ helpviewer_keywords:
- UseEventsWhereAppropriate
author: gewarren
ms.author: gewarren
dev_langs:
- CSharp
---
# CA1030: Use events where appropriate

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

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

## Example

:::code language="csharp" source="snippets/csharp/all-rules/ca1030.cs" id="snippet1":::

## When to suppress warnings

Suppress a warning from this rule if the method does not work with the .NET event model.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;

namespace ca1030
{
//<snippet1>
// This class violates the rule.
public class BadButton
{
private readonly List<Action> _clickHandlers = new List<Action>();

public void AddOnClick(Action handler)
{
// Some internal logic...

_clickHandlers.Add(handler);
}

public void RemoveOnClick(Action handler)
{
// Some internal logic...

_clickHandlers.Remove(handler);
}

public void FireClick()
{
foreach (Action handler in _clickHandlers)
{
handler();
}
}
}

// This class satisfies the rule.
public class GoodButton
{
private EventHandler? _clickHandler;

public event EventHandler? ClickHandler
{
add
{
// Some internal logic...

_clickHandler += value;
}
remove
{
// Some internal logic...

_clickHandler -= value;
}
}

protected virtual void OnClick(EventArgs e)
{
_clickHandler?.Invoke(this, e);
}

public void Click()
{
OnClick(EventArgs.Empty);
}
}
//</snippet1>
}