How to: Retrieve Custom Attributes 

You can retrieve custom attributes using the GetCustomAttribute or GetCustomAttributes methods of the Attribute class.

To retrieve a single instance of a custom attribute from a class

  1. Add an Imports statement to the top of your source code to import the Attribute class from the System namespace:

    Imports System.Attribute
    
  2. Create a procedure to retrieve the attribute:

    Sub RetrieveAttribute()
    
    End Sub
    
  3. Inside the procedure, declare a variable of type Attribute, and another variable of the same type as the attribute you wish to retrieve:

    Dim Attr As Attribute
    Dim CustAttr As CustomAttribute
    
  4. Use the GetType operator to pass the type of the class and attribute to a call to the GetCustomAttribute method, and then assign the returned value to the variable declared as Attribute:

    Attr = GetCustomAttribute(Me.GetType, _
                              GetType(CustomAttribute), False)
    
  5. Use the CType function to convert the attribute's data type from generic attribute to the specific attribute of the type you retrieved. Then assign the result to the variable declared as the custom attribute type:

    CustAttr = CType(Attr, CustomAttribute)
    
  6. Check to see if the attribute was retrieved, and if it was, use the fields, properties, and methods of the attribute:

    If CustAttr Is Nothing Then
        MsgBox("The attribute was not found.")
    Else
        'Get the label and value from the custom attribute.
        MsgBox("The attribute label is: " & CustAttr.Label)
        MsgBox("The attribute value is: " & CustAttr.Value)
    End If
    

    In the above example, the RetrieveAttribute procedure calls the GetCustomAttribute method of the System.Attribute class to get the custom attribute applied to the class ThisClass. GetCustomAttribute is a shared method, so you do not need to create an instance of System.Attribute first. The CType function converts the returned attribute from type System.Attribute to the custom attribute type CustomAttribute.

See Also

Tasks

How to: Define Your Own Attributes

Reference

GetType Operator
CType Function
IsNothing Function
GetAttr Function
GetCustomAttribute
GetCustomAttributes
AttributeUsageAttribute

Concepts

Application of Attributes
Retrieving Information Stored in Attributes