Attributes in Visual Basic
Attributes provide a powerful mechanism to add declarative information to your code. This information can be inspected at run time by using reflection. Attributes are essentially a type of metadata that can be applied to elements such as classes, methods, properties, and assemblies. They are defined as classes that inherit from the System.Attribute
class.
Understanding Attributes
Attributes are a form of declarative programming. Instead of describing how to do something, you describe something about the code. For example, an attribute can specify that a method should be executed at a certain time, or that a property should be serialized to a particular format. The .NET Framework provides many built-in attributes, and you can also create your own custom attributes.
Commonly Used Built-in Attributes
[Obsolete]
: Marks a code element as obsolete and provides an optional message to indicate why it's obsolete and what to use instead.[Serializable]
: Indicates that a class can be serialized.[DllImport]
: Used to call unmanaged functions from a DLL.[Conditional]
: Specifies that a method's execution depends on a given preprocessor symbol.[AttributeUsage]
: Controls how custom attributes can be applied.
Creating Custom Attributes
To create a custom attribute, you define a class that inherits from System.Attribute
. The naming convention for attribute classes is to append "Attribute" to the name you want to use when applying it (e.g., a class named MyCustomAttribute
would be applied using [MyCustom]
).
Example: Creating a Custom Author Attribute
This example demonstrates creating a simple custom attribute to store author information.
Imports System
' Define the custom attribute
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method, AllowMultiple:=False)>
Public Class AuthorAttribute
Inherits Attribute
Public ReadOnly Property Name As String
Public Property Version As String
' Constructor
Public Sub New(ByVal name As String)
Me.Name = name
Me.Version = "1.0" ' Default version
End Sub
End Class
' Apply the custom attribute to a class and a method
<Author("John Doe", Version:="1.1")>
Public Class MyClass
<Author("Jane Smith")>
Public Sub MyMethod()
Console.WriteLine("This is MyMethod.")
End Sub
End Class
Applying Attributes
Attributes are applied using square brackets []
immediately before the code element they apply to. You can specify attribute arguments within the parentheses.
Example: Applying Built-in Attributes
This shows the application of the [Obsolete]
attribute.
Public Class OldService
<Obsolete("This method is deprecated. Use NewMethod instead.", True)>
Public Sub OldMethod()
Console.WriteLine("This is an old method.")
End Sub
Public Sub NewMethod()
Console.WriteLine("This is the new method.")
End Sub
End Class
Attribute Usage Attribute
The <AttributeUsage>
attribute is used to control how and where your custom attributes can be applied. Key properties include:
AttributeTargets
: Specifies the code elements to which the attribute can be applied (e.g.,Class
,Method
,Property
,Assembly
).AllowMultiple
: A boolean indicating whether the attribute can be applied more than once to the same element.Inherited
: A boolean indicating whether the attribute is inherited by derived classes or overridden members.
Reflection and Attributes
Attributes are useful because their information can be retrieved at runtime using reflection. This allows you to build dynamic and extensible applications.
Example: Reading Attribute Information
This example shows how to read the custom AuthorAttribute
applied in a previous example.
Imports System.Reflection
Module AttributeReader
Sub Main()
Dim type As Type = GetType(MyClass)
' Get attributes applied to the class
Dim classAttributes As Object() = type.GetCustomAttributes(GetType(AuthorAttribute), False)
If classAttributes.Length > 0 Then
Dim authorAttr = DirectCast(classAttributes(0), AuthorAttribute)
Console.WriteLine($"Class {type.Name} authored by: {authorAttr.Name}, Version: {authorAttr.Version}")
End If
' Get attributes applied to methods
Dim methods As MethodInfo() = type.GetMethods()
For Each method In methods
Dim methodAttributes As Object() = method.GetCustomAttributes(GetType(AuthorAttribute), False)
If methodAttributes.Length > 0 Then
Dim authorAttr = DirectCast(methodAttributes(0), AuthorAttribute)
Console.WriteLine($" Method {method.Name} authored by: {authorAttr.Name}")
End If
Next
End Sub
End Module
Conclusion
Attributes are a powerful feature in VB.NET that enable you to embed metadata directly into your code. This metadata can be leveraged by the .NET Framework or your own applications to control behavior, provide information, and enhance code functionality. Understanding and utilizing attributes can lead to more robust, maintainable, and flexible software solutions.