C#idiomatic C#
ca1813fundamentals/code-analysis/quality-rules

Code analysis

CA1813: Avoid unsealed attributes

Learn about code analysis rule CA1813: Avoid unsealed attributes

CA1813 Performance enabled by default in .NET 10: No
Fix is breaking or non-breaking BreakingApplicable languages C# and Visual Basic

Cause

A public type inherits from System.Attribute, is not abstract, and is not sealed (NotInheritable in Visual Basic).

Rule description

.NET provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy. For example, System.Attribute.GetCustomAttribute searches for the specified attribute type or any attribute type that extends the specified attribute type. Sealing the attribute eliminates the search through the inheritance hierarchy, and can improve performance.

How to fix violations

To fix a violation of this rule, seal the attribute type or make it abstract.

When to suppress warnings

It is safe to suppress a warning from this rule. Suppress only if you are defining an attribute hierarchy and cannot seal the attribute or make it abstract.

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.

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

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

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

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

Example

The following example shows a custom attribute that satisfies this rule.

sample · csharpdocs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1813.cssnippet1

csharp
using System;

namespace ca1813
{
    //<snippet1>
    // Satisfies rule: AvoidUnsealedAttributes.
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
    public sealed class DeveloperAttribute : Attribute
    {
        public DeveloperAttribute(string name)
        {
            Name = name;
        }

        public string Name { get; }
    }
    //</snippet1>
}

sample · vbdocs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/ca1813-avoid-unsealed-attributes_1.vb

vb
Imports System

Namespace ca1813

    ' Satisfies rule: AvoidUnsealedAttributes.
    <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct)>
    Public NotInheritable Class DeveloperAttribute
        Inherits Attribute

        Public Sub New(name As String)
            Me.Name = name
        End Sub


        Public ReadOnly Property Name() As String
    End Class

End Namespace

See also