Attribute. 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).
Conditional example. 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.
Start We define the TEST constant at the top of the program with #Const. This is a compiler constant.
Result The TEST constant is defined, so the Conditional 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
Conditional, not compiled. Here we have the program that uses a Conditional attribute, but the compiler constant is set to 0. The Conditional Sub is not compiled.
Detail The 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
Obsolete attribute. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 22, 2023 (edit).