แก้ไข

แชร์ผ่าน


CA1058: Types should not extend certain base types

Property Value
Rule ID CA1058
Title Types should not extend certain base types
Category Design
Fix is breaking or non-breaking Breaking
Enabled by default in .NET 9 No

Cause

A type extends one of the following base types:

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

Rule description

Exceptions should derive from System.Exception or one of its subclasses in the System namespace.

Do not create a subclass of XmlDocument if you want to create an XML view of an underlying object model or data source.

Non-generic collections

Use and/or extend generic collections whenever possible. Do not extend non-generic collections in your code, unless you shipped it previously.

Examples of Incorrect Usage

public class MyCollection : CollectionBase
{
}

public class MyReadOnlyCollection : ReadOnlyCollectionBase
{
}

Examples of Correct Usage

public class MyCollection : Collection<T>
{
}

public class MyReadOnlyCollection : ReadOnlyCollection<T>
{
}

How to fix violations

To fix a violation of this rule, derive the type from a different base type or a generic collection.

When to suppress warnings

Do not suppress a warning from this rule for violations about ApplicationException. It is safe to suppress a warning from this rule for violations about XmlDocument. It is safe to suppress a warning about a non-generic collection if the code was released previously.

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

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

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