Creating Custom Attributes (C# and Visual Basic)
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 types with the name of the programmer who wrote the type. 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 example, name is a positional parameter. 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 (Structure in Visual Basic) 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. In the following code example, a multiuse attribute is created.
In the following code example, multiple attributes of the same type are applied to a class.
Note
|
|---|
|
If your attribute class contains a property, that property must be read-write. |
Note