This documentation is archived and is not being maintained.

5. Attributes

Visual Studio .NET 2003

The Visual Basic .NET language enables the programmer to specify modifiers on declarations, which represent information about the entities being declared. For example, affixing a class method with the modifiers Public, Protected, Friend, Protected Friend, or Private specifies its accessibility.

In addition to the modifiers defined by the language, Visual Basic .NET also enables programmers to create new modifiers, called attributes, and to use them when declaring new entities. These new modifiers, which are defined through the declaration of attribute classes, are then assigned to entities through attribute blocks.

Note   Attributes may be retrieved at run time through the .NET Framework's reflection APIs. These APIs are outside the scope of this specification.

For instance, a framework might define a Help attribute that can be placed on program elements such as classes and methods to provide a mapping from program elements to documentation, as the following example demonstrates:

Imports System

<AttributeUsage(AttributeTargets.All)> _
Public Class HelpAttribute
    Inherits Attribute

    Public Sub New(ByVal UrlValue As String)
        Me.UrlValue = UrlValue
    End Sub

    Public Topic As String
    Private UrlValue As String

    Public ReadOnly Property Url() As String
            Return UrlValue
        End Get
    End Property
End Class

The example defines an attribute class named HelpAttribute, or Help for short, that has one positional parameter (UrlValue) and one named argument (Topic).

The next example shows several uses of the attribute:

<Help("")> _
Public Class Class1
    <Help("", Topic := "F")> _
        Public Sub F()
    End Sub
End Class

The next example checks to see if Class1 has a Help attribute, and writes out the associated Topic and Url values if the attribute is present.

Imports System

Module Test
    Sub Main()
        Dim type As Type = GetType(Class1)
        Dim arr() As Object() = _
            type.GetCustomAttributes(GetType(HelpAttribute), True)

        If arr.Length = 0 Then
            Console.WriteLine("Class1 has no Help attribute.")
            Dim ha As HelpAttribute = CType(arr(0), HelpAttribute)
            Console.WriteLine("Url = " & ha.Url & "Topic = " & ha.Topic)
        End If
    End Sub
End Module

See Also

4.1 Declarations | 4.3 Inheritance | 4.4 Implementation | 4.5 Polymorphism | 4.6 Accessibility | 4.2 Scope | 4.7 Type and Namespace Names | Attributes (Visual Basic Language Concepts)