Information Technology Reference
In-Depth Information
Using Custom Attributes
Now that you've seen how attributes are applied, you've probably noticed that the syntax is
very different from anything else you've seen so far. From that, you might get the impression
that attributes are an entirely different type of construct. They're not—they are just a special
kind of class.
Some important points about attribute classes are the following:
User-defined attribute classes are called
custom attributes
.
Attribute classes are derived from class
System.Attribute
.
Attribute names, by convention, use Pascal casing, and end with the suffix
Attribute
.
When applying an attribute to a target, you can leave off the suffix. For example, if you
were to look at the declarations of attributes
Serializable
and
MyAttribute
, which I used
in previous examples, you would find that they are actually named
SerializableAttribute
and
MyAttributeAttribute
.
Declaring a Custom Attribute
Declaring an attribute class is, for the most part, the same as declaring any other class. There
are, however, several things to be aware of.
To declare a custom attribute, do the following:
-
Declare a class derived from
System.Attribute
.
-
Give it a name ending with the suffix
Attribute
.
For security, it is a generally suggested that you declare your attribute classes as
sealed
.
For example, the following code shows the beginning of the declaration of attribute
MyAttributeAttribute
.
Attribute name
↓
public sealed class MyAttributeAttribute :
System
.
Attribute
{
↑
↑
...
Suffix
Base class
Since an attribute holds information about the target, the public members of an attribute
class generally consist only of the following:
Fields
Proper ies
Constructors