diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1030.md b/docs/fundamentals/code-analysis/quality-rules/ca1030.md index be21728d0c6c5..eb362505f696b 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1030.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1030.md @@ -10,6 +10,8 @@ helpviewer_keywords: - UseEventsWhereAppropriate author: gewarren ms.author: gewarren +dev_langs: +- CSharp --- # CA1030: Use events where appropriate @@ -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. diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1030.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1030.cs new file mode 100644 index 0000000000000..860d616955626 --- /dev/null +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1030.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; + +namespace ca1030 +{ + // + // This class violates the rule. + public class BadButton + { + private readonly List _clickHandlers = new List(); + + 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); + } + } + // +}