VB.NET Directive Examples: Const, If and Region

Understand the syntax for directives. Use the Const, If and Region directives.
Directives modify programs in an early stage of compilation. The #Const directive defines a value that can be used throughout a program. And the #If directive can test those constants. Other directives, like #Region, are also available.
Const, If. This program uses the #Const directive to define a symbol. It sets the SPECIAL symbol to the value 1. Inside the Main Sub, we use an #If directive to test the value of SPECIAL. A code statement is enclosed in the #If block.

So: When SPECIAL is equal to 1, the variable "a" is assigned to the value 2. Other values of SPECIAL do not have this effect.

Example: We use preprocessor directives, which begin with the pound character "#". These directives start at the first character in a line.

Info: They are not the same as the Const and If keywords used in compiled VB.NET code.

ConstIf Then
VB.NET program that uses directives #Const SPECIAL = 1 Module Module1 Sub Main() ' Local variable. Dim a As Integer = 1 ' Use special value is SPECIAL is 1. #If SPECIAL = 1 Then a = 2 #End If ' Display value. Console.WriteLine(a) End Sub End Module Output 2
Region. Another directive available in VB.NET programs is #Region. This directive partitions a code file. It has no effect on the compiled program. We use #Region to organize code. In Visual Studio, a region can be collapsed and expanded.

Also: Regions are used by Visual Studio when auto-generation of code files is performed, as for Windows Forms.

Note: Regions in VB.NET cannot be used in all locations. They must enclose an entire Function body or other unit of code.

VB.NET program that uses Region Module Module1 #Region "INIT" ''' <summary> ''' Initialize the program. ''' </summary> Sub Main() Console.WriteLine("A") Console.WriteLine("B") Console.WriteLine("C") Console.WriteLine("Copyright 2017") End Sub #End Region End Module Output A B C Copyright 2017
Discussion. Preprocessing directives are handled at an early stage of compilation. The preprocessor scans VB.NET programs before compiling code statements into intermediate language. They are separate. This gives them special abilities.

And: With preprocessing directives, no performance loss is incurred with branches of an #If. The branches are handled before execution.

Caution: One problem with preprocessing directives is bit rot. Code that is not compiled because of an #If may become buggy or invalid.

Summary. Directives add another layer of compilation to VB.NET programs. They can be considered a program on top of an actual VB.NET program. With #If, #Const and even #Region, we access another set of abilities in this language.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls