Information Technology Reference
In-Depth Information
Using Attribute Constructors
Attributes, like other classes, have constructors. Every attribute must have at least one public
constructor.
As with other classes, if you don't declare a constructor, the compiler will produce an
implicit, public, parameterless constructor for you.
Attribute constructors, like other constructors, can be overloaded.
When declaring the constructor, you must use the full class name, including the suffix.
You can use the shortened name only when
applying
an attribute.
For example, with the following code, the compiler would produce an error message if the
constructor name did not include the suffix.
Suffix
↓
public MyAttributeAttribute(string desc, string ver)
{
Description = desc;
VersionNumber = ver;
}
Specifying the Constructor
When you apply an attribute to a target, you are specifying which attribute constructor should
be used to create the instance of the attribute. The parameters listed in the attribute applica-
tion are the actual parameters for the constructor.
For example, in the following code,
MyAttribute
is applied to a field and to a method. For
the field, the declaration specifies a constructor with a single
string
parameter. For the
method, it specifies a constructor with two
string
parameters.
[MyAttribute("Holds a value")] // Constructor with one string
public int MyField;
[MyAttribute("Version 1.3", "Sal Martin")] // Constructor with two strings
public void MyMethod()
{ ...