Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

AttributeUsageAttribute — rules for custom attributes

AttributeUsageAttribute specifies where a custom attribute may be applied, whether it may be repeated, and whether it is inherited. AttributeTargets.Property restricts its use to properties.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]

System.AttributeUsageAttribute, written as [AttributeUsage(...)], is placed on a custom attribute class derived from Attribute. It defines rules for applying that attribute, not the behavior of objects marked with it.

The constructor argument of type AttributeTargets determines the read-only ValidOn property. This is a flags enumeration: combine targets with |, for example AttributeTargets.Property | AttributeTargets.Field. AttributeTargets.Property alone permits properties, not fields or the get and set accessor methods. An invalid target causes a compilation error.

AllowMultiple controls whether the attribute can appear repeatedly on one element; its default is false. Inherited controls attribute inheritance by derived classes and overriding members; its default is true. This does not mean inheritance of the attribute class itself. Default rules without an explicit restriction correspond to AttributeTargets.All, AllowMultiple = false, Inherited = true.

In the example, LabelAttribute can appear only once on a property and is not inherited. [Label("Product name")] records metadata on Name; the code reads it through reflection. The attribute itself does not validate the property's value. The APIs used are available in .NET 10; the example does not require preview language features.

Examples

using System;

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public sealed class LabelAttribute : Attribute
{
    public LabelAttribute(string text) => Text = text;
    public string Text { get; }
}

public sealed class Product
{
    [Label("Product name")]
    public string Name { get; set; } = "";
}

public static class Program
{
    public static void Main()
    {
        var property = typeof(Product).GetProperty(nameof(Product.Name))!;
        var label = (LabelAttribute)Attribute.GetCustomAttribute(
            property, typeof(LabelAttribute))!;
        Console.WriteLine(label.Text);
    }
}

Result

Product name

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources