S3993 — Custom attributes should be marked with "System.AttributeUsageAttribute"

Language
C#
Type
Code smell
Severity
Major
Tags
api-design

Why is this an issue?

When defining custom attributes, AttributeUsageAttribute must be used to indicate where the attribute can be applied. This will:

How to fix it

Code examples

Noncompliant code example


public sealed class MyAttribute : Attribute // Noncompliant - AttributeUsage is missing
{
    private string text;

    public MyAttribute(string text)
    {
        this.text = text;
    }

    public string Text => text;
}

Compliant solution


[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate)]
public sealed class MyAttribute : Attribute
{
    private string text;

    public MyAttribute(string text)
    {
        this.text = text;
    }

    public string Text => text;
}

Resources

Documentation

↑ Back to top