แก้ไข

แชร์ผ่าน


CA1030: Use events where appropriate

Property Value
Rule ID CA1030
Title Use events where appropriate
Category Design
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 No

Cause

A method name begins with one of the following:

  • AddOn
  • RemoveOn
  • Fire
  • Raise

By default, this rule only looks at externally visible methods, but this is configurable.

Rule description

This rule detects methods that have names that ordinarily would be used for events. Events follow the Observer or Publish-Subscribe design pattern; they are used when a state change in one object must be communicated to other objects. If a method gets called in response to a clearly defined state change, the method should be invoked by an event handler. Objects that call the method should raise events instead of calling the method directly.

Some common examples of events are found in user interface applications where a user action such as clicking a button causes a segment of code to execute. The .NET event model is not limited to user interfaces. It should be used anywhere you must communicate state changes to one or more objects.

How to fix violations

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

When to suppress warnings

Suppress a warning from this rule if the method does not work with the .NET event model.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA1030
// The code that's violating the rule is on this line.
#pragma warning restore CA1030

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA1030.severity = none

For more information, see How to suppress code analysis warnings.

Configure code to analyze

Use the following option to configure which parts of your codebase to run this rule on.

You can configure this option for just this rule, for all rules it applies to, or for all rules in this category (Design) that it applies to. For more information, see Code quality rule configuration options.

Include specific API surfaces

You can configure which parts of your codebase to run this rule on, based on their accessibility. For example, to specify that the rule should run only against the non-public API surface, add the following key-value pair to an .editorconfig file in your project:

dotnet_code_quality.CAXXXX.api_surface = private, internal