Muokkaa

Jaa


CA1070: Do not declare event fields as virtual

Property Value
Rule ID CA1070
Title Do not declare event fields as virtual
Category Design
Fix is breaking or non-breaking Breaking
Enabled by default in .NET 9 As suggestion

Cause

A field-like event was declared as virtual.

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

Rule description

Follow these .NET design guidelines to raise base class events in derived classes. Do not declare virtual events in a base class. Overridden events in a derived class have undefined behavior. The C# compiler does not handle this correctly and it is unpredictable whether a subscriber to the derived event will actually be subscribing to the base class event.

using System;
public class C
{
    // CA1070: Event 'ThresholdReached' should not be declared virtual.
    public virtual event EventHandler ThresholdReached;
}

How to fix violations

Follow these .NET design guidelines and avoid virtual field-like events.

When to suppress warnings

If the event is an externally visible public API that is already part of a shipped library, then it is safe to suppress a warning from this rule to avoid a breaking change for the library consumers.

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 CA1070
// The code that's violating the rule is on this line.
#pragma warning restore CA1070

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

[*.{cs,vb}]
dotnet_diagnostic.CA1070.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

See also