In the .NET platform, and therefore in Visual Basic, attributes were introduced as a powerful tool for annotating various code elements with metadata. This allows programs and tools to gain additional information at runtime and compile time, configuring the behavior of methods, classes, and properties through reflection, serialization, automated testing, and so on.
Without attributes, one has to hard-code additional logic for configuring methods or classes, and generic libraries cannot be extensible and flexible without external information about the class or method. There's also the issue of passing settings without changing the actual code.
Attributes are special classes that inherit from Attribute. They can be created and applied to methods, classes, properties, parameters, or return values. At runtime, these attributes can be discovered through reflection and modify the behavior of the corresponding logic.
Example code for creating and using a custom attribute:
Imports System <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method, AllowMultiple:=False)> Public Class InfoAttribute Inherits Attribute Public Property Description As String Public Sub New(desc As String) Description = desc End Sub End Class <Info("Special business logic method.")> Public Sub Calculate() Console.WriteLine("Calculation performed.") End Sub ' Reading the attribute via reflection Dim method = GetType(Module1).GetMethod("Calculate") Dim attr = CType(Attribute.GetCustomAttribute(method, GetType(InfoAttribute)), InfoAttribute) If attr IsNot Nothing Then Console.WriteLine(attr.Description)
Key features:
AttributeTargets.Class, Method, Property, etc.)Can attributes directly change the behavior of a method or class without using reflection?
No, attributes themselves contain only metadata. The behavior of an object can only be changed if the calling code or runtime checks for the presence of the attribute via reflection and takes additional actions.
Can the same attribute be applied multiple times to the same element, and what is required for this?
By default — no. To allow this upon declaration of the attribute, AllowMultiple:=True must be specified in AttributeUsage. Then one attribute can be applied multiple times to one element.
Are attributes inherited from base class to derived class?
No, by default — they are not inherited. If inheritance is required, the AttributeUsage specifies the parameter Inherited:=True.
In a project, custom attributes are mass-applied to methods, but no one implements processing of these attributes through reflection — such code becomes a useless burden, complicating maintenance and readability of the source code.
Pros:
Cons:
An attribute is used for annotating logging methods, and a separate subsystem automatically determines, through reflection, which methods are subject to auditing, inserts analytics, and adds tracing. The behavior is transparent to the user.
Pros:
Cons: