Creating Custom Attributes Attributes

107

2.22.1 Creating Custom Attributes

The attribute mechanism is extensible. A new attribute is defined by declaring a class that derives from the Attribute type in the System namespace and that provides an indication of what declarations the attribute should be allowed to modify. Heres an example: AttributeUsageAttributeTargets.All Public Class SomeAttribute Inherits System.Attribute End Class This code defines an attribute called SomeAttribute . The SomeAttribute class itself is modified by the AttributeUsage attribute. The AttributeUsage attribute is a standard .NET Framework attribute that indicates which declarations can be modified by the new attribute. In this case, the value of AttributeTargets.All indicates that the SomeAttribute attribute can be applied to any and all declarations. The argument of the AttributeUsage attribute is of type AttributeTargets defined in the System namespace. The values in this enumeration are: Assembly , Module , Class , Struct , Enum , Constructor , Method , Property , Field , Event , Interface , Parameter , Delegate , ReturnValue , and All . To create an attribute that takes one or more arguments, add a parameterized constructor to the attribute class. Heres an example: AttributeUsageAttributeTargets.Method _ Public Class MethodDocumentationAttribute Inherits System.Attribute Public ReadOnly Author As String Public ReadOnly Description As String Public Sub NewByVal Author As String, ByVal Description As String Me.Author = Author Me.Description = Description End Sub End Class This code defines an attribute that takes two parameters: Author and Description . It could be used to modify a method declaration like this: MethodDocumentationDave Grundgeiger, This is my method. _ Public Sub SomeMethod ... End Sub By convention, attribute names end with the word Attribute . Visual Basic .NET references attributes either by their full names—for example, MethodDocumentationAttribute —or by their names less the trailing Attribute —for example, MethodDocumentation . Attributes whose names do not end with the word Attribute are simply referenced by their full names.

2.22.2 Reading Attributes