CA1813: Avoid unsealed attributes

 

The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at CA1813: Avoid unsealed attributes.

TypeName|AvoidUnsealedAttributes|
|CheckId|CA1813|
|Category|Microsoft.Performance|
|Breaking Change|Breaking|

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

The .NET Framework class library provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy; for example 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.

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

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.

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;
            }
        }
    }

}

CA1019: Define accessors for attribute arguments

CA1018: Mark attributes with AttributeUsageAttribute

Attributes

Show: