Edit

Share via


CA1852: Seal internal types

Property Value
Rule ID CA1852
Title Seal internal types
Category Performance
Fix is breaking or non-breaking Non-breaking
Introduced version .NET 7
Enabled by default in .NET 8 No

Cause

A type that's not accessible outside its assembly and has no subtypes within its containing assembly is not marked sealed (NotInheritable in Visual Basic).

Rule description

When a type isn't accessible outside its assembly and has no subtypes within its containing assembly, it can be safely sealed. Sealing types can improve performance. For more information, see Analyzer Proposal: Seal internal/private types].

If you apply System.Runtime.CompilerServices.InternalsVisibleToAttribute to the assembly that's being analyzed, this rule doesn't flag types that aren't marked as sealed by default, because a field may be used by a friend assembly. To analyze the assembly anyway, see Configure code to analyze.

How to fix violations

Mark the type as sealed (NotInheritable in Visual Basic).

Example

The following code snippet shows a violation of CA1852:

internal class C
{ }
Class C
End Class

The following code snippet fixes the violation:

internal sealed class C
{ }
NotInheritable Class C
End Class

When to suppress warnings

It's safe to suppress a warning if performance isn't a concern.

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

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

[*.{cs,vb}]
dotnet_diagnostic.CA1852.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 (Performance) that it applies to. For more information, see Code quality rule configuration options.

Ignore InternalsVisibleTo attribute

By default, this rule is disabled if the assembly being analyzed uses InternalsVisibleToAttribute to expose its internal symbols. To specify that the rule should run even if the assembly is marked with InternalsVisibleToAttribute, add the following key-value pair to an .editorconfig file in your project:

dotnet_code_quality.CAXXXX.ignore_internalsvisibleto = true

This option is available starting in .NET 8.