O'Reilly logo

VB.NET Language in a Nutshell, Second Edition by Steven Roman PhD, Paul Lomax, Ron Petrusha

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required