Custom Attributes in Visual Basic
Custom attributes are user-defined attributes that provide additional information about program elements. For example, you might define a custom security attribute that specifies the permissions required by the caller to execute a procedure.
You define custom attributes in attribute classes based on the System.Attribute class. Attribute classes themselves use an attribute called AttributeUsageAttribute to provide information about how the attribute can be used. Specifying Inherited = True
indicates that an attribute can propagate to derived classes. Setting the AllowMultiple property to True allows you to apply more than one instance of the attribute to a program element. The AttributeTargets enumeration lets you define which kinds of program elements your attribute can apply to.
In the following code, the AttributeUsageAttribute attribute specifies an attribute that can be applied to any type of item, inherited, and applied only once:
<AttributeUsage(AttributeTargets.All, Inherited:=True, AllowMultiple:=False)> _
Class TestAttribute1
Inherits Attribute
End Class
You can use the Or operator to combine multiple items from the AttributeTargets enumeration, as in the following code:
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method)> _
Class TestAttribute2
Inherits Attribute
End Class
In This Section
- How to: Define Your Own Attributes
Explains how to create your own attributes using attribute classes.
- How to: Retrieve Custom Attributes
Demonstrates how to retrieve custom attributes using GetCustomAttribute or GetCustomAttributes.
- Examples of Custom Attribute Usage
Provides example code that defines a custom attribute that can be applied only to classes, and shows how to use the new attribute.
Related Sections
- Visual Basic and the .NET Framework
Describes the role of Visual Basic in the .NET Framework.
- Object-Oriented Programming in Visual Basic
Provides information about object-oriented programming and how it is used.
- Metadata and Self-Describing Components
Provides detailed information about the kinds of metadata used in Visual Studio, including attributes.