Defining a Custom Attribute

An attribute is merely a class that inherits from System.Attribute, which makes it very easy to implement a custom attribute. In this section, we’ll build a custom attribute called <DeveloperNote>, which allows a developer to add assorted information (the developer’s name, the date, a comment, and whether a code modification was a response to a bug) to code. The steps are as follows:

  1. Define a public class that inherits from System.Attribute or another attribute class derived from System.Attribute. For example:

    Public Class DeveloperNoteAttribute
     Inherits System.Attribute

    Note that, by convention, the name of the class ends with the substring “Attribute”.

  2. Apply the <AttributeUsage> attribute, which defines the language elements to which the custom attribute can be applied, to the class (as shown in the following code fragment). The attribute’s only required argument is one of the following members of the AttributeTargets enumeration:

    All
    Assembly
    Class
    Constructor
    Delegate
    Enum
    Event
    Field
    Interface
    Method
    Module
    Parameter
    Property
    ReturnValue
    Struct

    If an attribute applies to multiple programming elements, but not all elements, the relevant constants can be ORed together. In the case of our <DeveloperNote> attribute, we want the attribute to apply to all program elements. In addition, we want to make the <DeveloperNote> attribute extensible through inheritance, so we set the <AttributeTarget> attribute’s Inherited argument to True. Finally, ...

Get VB.NET Language in a Nutshell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.