Visual Basic .NET - Custom Attributes in VB.NET

Custom attributes in VB.NET are a powerful feature that allows developers to add metadata (extra information) to classes, methods, properties, assemblies, or other program elements. This metadata is not directly part of the program logic but can be accessed at runtime using reflection. It is especially useful for building frameworks, validation systems, logging mechanisms, and configuration-driven applications.


What is an Attribute?

An attribute is essentially a class that inherits from the base class System.Attribute. It is used to attach declarative information to code elements. VB.NET already provides built-in attributes such as Obsolete, Serializable, and DllImport, but developers can also create their own custom attributes to suit specific needs.


Why Use Custom Attributes?

Custom attributes are used to:

  • Add descriptive information to code elements

  • Control runtime behavior dynamically

  • Enable validation rules without hardcoding logic

  • Support aspect-oriented programming concepts

  • Simplify configuration and reduce repetitive code

For example, you can create an attribute to mark required fields, log method execution, or define access permissions.


Creating a Custom Attribute

To create a custom attribute in VB.NET, you define a class that inherits from System.Attribute.

Example:

<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method)>
Public Class MyCustomAttribute
    Inherits Attribute

    Public Property Description As String

    Public Sub New(desc As String)
        Description = desc
    End Sub
End Class

Explanation:

  • AttributeUsage specifies where the attribute can be applied (class, method, etc.)

  • The class inherits from Attribute

  • A constructor is used to pass values when applying the attribute

  • Properties store attribute data


Applying a Custom Attribute

Once defined, the attribute can be applied using angle brackets.

Example:

<MyCustom("This is a sample class")>
Public Class TestClass
End Class

You can also apply it to methods:

<MyCustom("This method performs addition")>
Public Sub Add()
End Sub

Accessing Custom Attributes at Runtime

Custom attributes become useful when you retrieve them using reflection.

Example:

Dim type As Type = GetType(TestClass)
Dim attributes() As Object = type.GetCustomAttributes(False)

For Each attr In attributes
    If TypeOf attr Is MyCustomAttribute Then
        Dim customAttr As MyCustomAttribute = CType(attr, MyCustomAttribute)
        Console.WriteLine(customAttr.Description)
    End If
Next

Explanation:

  • GetType() retrieves metadata about the class

  • GetCustomAttributes() returns applied attributes

  • You check the attribute type and access its properties


AttributeUsage Options

The AttributeUsage attribute controls how a custom attribute behaves.

Key options include:

  • AttributeTargets: Defines where the attribute can be applied (Class, Method, Property, etc.)

  • AllowMultiple: Allows multiple instances of the same attribute

  • Inherited: Determines if the attribute is inherited by derived classes

Example:

<AttributeUsage(AttributeTargets.Method, AllowMultiple:=True)>

Real-World Use Cases

  1. Validation Systems
    Custom attributes can define rules like Required or MaxLength and validate objects dynamically.

  2. Logging and Monitoring
    Mark methods that need logging without modifying the method body.

  3. Role-Based Access Control
    Define user roles required to execute certain methods.

  4. Serialization Control
    Specify which properties should be included or ignored during serialization.

  5. Framework Development
    Many frameworks rely heavily on attributes to configure behavior declaratively.


Advantages of Custom Attributes

  • Promotes clean and maintainable code

  • Separates logic from metadata

  • Enables dynamic behavior without modifying core logic

  • Reduces code duplication


Limitations

  • Requires reflection, which can impact performance if overused

  • Metadata is passive unless explicitly processed

  • Can make code harder to understand if overused or poorly documented


Conclusion

Custom attributes in VB.NET provide a flexible way to extend the functionality of applications by embedding metadata directly into code. They are widely used in modern application development for validation, configuration, and dynamic behavior control. When combined with reflection, they enable developers to build highly scalable and maintainable systems without cluttering business logic.