Information Technology Reference
In-Depth Information
Other important points about attribute constructors are the following:
When applying an attribute, the actual parameters for the constructor must be constant
expressions whose values can be determined at compile time.
If you are applying an attribute constructor with no parameters, you can leave off the
parentheses. For example, both classes in the following code use the parameterless con-
structor for the attribute
MyAttr
. The meaning of the two forms is the same.
[MyAttr]
class SomeClass ...
[MyAttr()]
class OtherClass ...
Using the Constructor
As with other classes, you cannot call the constructor explicitly. An instance of an attribute is
created, and a constructor called, only when an attribute consumer accesses the attribute.
This is very different from other classes, which are created at the position where you used
an object-creation expression. Applying an attribute is a declarative statement that does not
determine when an object of the attribute class should be constructed.
Figure 21-3 compares the use of a constructor for a regular class and the use of a construc-
tor with attributes.
The imperative statement says, in effect, “Create a new class object here.”
The declarative statement says, “This attribute is associated with this target, and in case
the attribute needs to be constructed—use this constructor.”
Figure 21-3.
Comparing the use of constructors