|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
Creating Custom Attributes (C# Programming Guide)
Updated: July 2008
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. 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:
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:
AttributeUsage has a named parameter, AllowMultiple, with which you can make a custom attribute single-use or multiuse.
If your attribute class contains a property, that property must be read-write. Write-only properties are not supported in attribute classes in C#.