Creating Custom Attributes (C# Programming Guide)
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:
[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;
}
}
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 SampleClass
{
// H. Ackerman's code goes here...
}
AttributeUsage has a named parameter, AllowMultiple, with which you can make a custom attribute single-use or multiuse.
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct,
AllowMultiple = true) // multiuse attribute
]
public class Author : System.Attribute
[Author("H. Ackerman", version = 1.1)]
[Author("M. Knott", version = 1.2)]
class SampleClass
{
// H. Ackerman's code goes here...
// M. Knott's code goes here...
}
Note
If your attribute class contains a property, that property must be read-write. Write-only properties are not supported in attribute classes in C#.
See Also
Concepts
Reference
Reflection (C# Programming Guide)
Attributes (C# Programming Guide)
Using Attributes (C# Programming Guide)
Disambiguating Attribute Targets (C# Programming Guide)
Accessing Attributes With Reflection (C# Programming Guide)
Change History
Date |
History |
Reason |
---|---|---|
July 2008 |
Added note about property support. |
Content bug fix. |