HomeSearch

VB.NET Attribute Examples

Use attribute syntax to influence compilation. Specify subroutines as Conditional or Obsolete.

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.

Const: We define the TEST constant at the top of the program with #Const. This is a compiler constant.

Directives

Result: The TEST constant is defined, so the Conditional Sub is compiled and executed at runtime. The field is assigned the value 100.

VB.NET program that uses Conditional attribute #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 Module Output VALUE 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.

So: The Test() sub is never executed. The value is never set to 100, and it retains is default value of 0 at runtime.

VB.NET program that uses Conditional, not compiled #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 Module Output VALUE 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.
VB.NET program that uses Obsolete attribute 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 Module Output Warning 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.Enum

A review. 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.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.