Avoid excessive inheritance
Avoid excessive inheritance
Microsoft docsDescription
Deeply nested type hierarchies can be difficult to follow, understand, and maintain. This rule limits analysis to hierarchies in the same module.
You can configure this rule in the following ways:
- By default, the rule excludes types from the
Systemnamespace. You can configure the rule to exclude other types or namespaces as well. - You can configure the inheritance tree depth at which this rule fires.
Cause
A type is five or more levels deep in its inheritance hierarchy.
How to fix violations
To fix a violation of this rule, derive the type from a base type that is less deep in the inheritance hierarchy or eliminate some of the intermediate base types.
Example
class BaseClass {}
class FirstDerivedClass : BaseClass {}
class SecondDerivedClass : FirstDerivedClass {}
class ThirdDerivedClass : SecondDerivedClass {}
class FourthDerivedClass : ThirdDerivedClass {}
// This class violates the rule.
class FifthDerivedClass : FourthDerivedClass {}When to suppress
It's safe to suppress a warning from this rule. However, the code might be more difficult to maintain. Depending on the visibility of base types, resolving violations of this rule might create breaking changes. For example, removing public base types is a breaking change. You might see false positive warnings from this rule if all of the following apply:
- You're using Visual Studio 2022 version 17.5 or later with an older version of the .NET SDK, that is, .NET 6 or earlier.
- You're using the analyzers from the .NET 6 SDK or an older version of the analyzer packages, such as Microsoft.CodeAnalysis.FxCopAnalyzers.
The false positives are due to a breaking change in the C# compiler. Consider using a newer analyzer that contains the fix for the false positive warnings. Upgrade to Microsoft.CodeAnalysis.NetAnalyzers version 7.0.0-preview1.22464.1 or newer or use the analyzers from the .NET 7 SDK.