Custom attributes

You can create your own custom attributes by defining an attribute class, a class that derives directly or indirectly from Attribute, which makes identifying attribute definitions in metadata fast and easy.

Example

[System.AttributeUsage(System.AttributeTargets.Class |  
                       System.AttributeTargets.Struct)  
]  
public class Author : System.Attribute  
{  
    private string name;  
    public double version;  
  
    public Author(string name)  
    {  
        this.name = name;  
        version = 1.0;  
    }  
}  

You could use this new attribute as follows:

[Author("P. Ackerman", version = 1.1)]  
class SampleClass  
{  
    // P. Ackerman's code goes here...  
}  

AllowMultiple

AttributeUsage has a named parameter, AllowMultiple, with which you can make a custom attribute single-use or multiuse.

In the following code example, multiple attributes of the same type are applied to a class.

Attribute usage

The AttributeUsageAttribute class has a public constructor that allows you to pass bit flags that indicate where your attribute can legally be applied . The System.AttributeTargets enumerated type is defined as follows:

Last updated