This documentation is archived and is not being maintained.

Creating Custom Attributes

You can create your own custom attributes by defining an attribute class, a class that derives directly or indirectly from System.Attribute (which makes identifying attribute definitions in metadata fast and easy). Suppose you want to tag classes and structs with the name of the programmer who wrote the class or struct. You might define a custom Author attribute class:

using System;
public class Author : Attribute
   public Author(string name) { = name; version = 1.0; }
   public double version;
   string name;

The class name is the attribute's name, Author. It is derived from System.Attribute, so it is a custom attribute class. The constructor's parameters are the custom attribute's positional parameters (in this case, name), and any public read-write fields or properties are named parameters (in this case, version is the only named parameter). Note the use of the AttributeUsage attribute to make the Author attribute valid only on class and struct declarations.

You could use this new attribute as follows:

[Author("H. Ackerman", version=1.1)] class SomeClass{...}

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

   AllowMultiple=true)] // multiuse attribute
public class Author : Attribute

See Also

Introduction to Attributes | Using Attributes | Attribute Targets | Global Attributes | Retrieving Attribute Information | AttributeUsage