A VB.NET program is compiled—once compiled, it is executed. With Attributes, we can affect the compilation phase. We can change what code is executed based on attributes.
With various attributes, we can specify a Subroutine is only executed if a #Const is defined (Conditional). Or we can warn that a Function is no longer the best choice (Obsolete).
Here we use the Conditional attribute. We specify the attribute on a Sub
called Test. We use the string
value "TEST" in the Conditional attribute's argument list.
Sub
is compiled and executed at runtime. The field is assigned the value 100.#Const TEST = 1 Module Module1 Dim _value As Integer <Conditional("TEST")> Sub Test() _value = 100 End Sub Sub Main() Test() Console.WriteLine("VALUE IS {0}", _value) End Sub End ModuleVALUE IS 100
Here we have the program that uses a Conditional attribute, but the compiler constant is set to 0. The Conditional Sub
is not compiled.
Test()
sub is never executed. The value is never set to 100, and it retains is default value of 0 at runtime.#Const TEST = 0 Module Module1 Dim _value As Integer <Conditional("TEST")> Sub Test() _value = 100 End Sub Sub Main() Test() Console.WriteLine("VALUE IS {0}", _value) End Sub End ModuleVALUE IS 0
Support we have a Sub
that we do not want to use anymore—it is not a good Sub
to call for some reason. We can use the Obsolete attribute to indicate this.
Module Module1 <Obsolete> Sub Test() ' Empty. End Sub Sub Main() ' The compiler will issue a warning if we call this obsolete Sub. Test() End Sub End ModuleWarning BC40008 'Public Sub Test()' is obsolete.
Enum
Flags
We can use the Flags
attribute on an Enum
type. This allows us to specify a single enum
value can have zero, one, or multiple values at once.
Attributes are specified in angle brackets in VB.NET. We can use built-in attributes like Conditional and Obsolete to change how a program is compiled.