Share via


CA1813: Avoid unsealed attributes

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Item Value
TypeName AvoidUnsealedAttributes
CheckId CA1813
Category Microsoft.Performance
Breaking Change Breaking

Cause

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

Rule Description

The .NET Framework class library 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. You should do this only if you are defining an attribute hierarchy and cannot seal the attribute or make it abstract.

Example

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

using System;

namespace PerformanceLibrary 
{
    // Satisfies rule: AvoidUnsealedAttributes.

    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)]
    public sealed class DeveloperAttribute: Attribute
    {
        private string nameValue;
        public DeveloperAttribute(string name) 
        { 
            nameValue = name; 
        }
        
        public string Name
        {
            get 
            {
                return nameValue;
            }
        }
    }

}
Imports System

Namespace PerformanceLibrary

' Satisfies rule: AvoidUnsealedAttributes.
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct)>  _
NotInheritable Public Class DeveloperAttribute
    Inherits Attribute
    Private nameValue As String
    
    Public Sub New(name As String)
        nameValue = name
    End Sub
    
    
    Public ReadOnly Property Name() As String
        Get
            Return nameValue
        End Get
    End Property
End Class 

End Namespace

CA1019: Define accessors for attribute arguments

CA1018: Mark attributes with AttributeUsageAttribute

See Also

Attributes