VB.NET Directive Examples: Const, If and RegionUnderstand 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.
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
' Local variable.
Dim a As Integer = 1
' Use special value is SPECIAL is 1.
#If SPECIAL = 1 Then
a = 2
' Display value.
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
''' Initialize the program.
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 firstname.lastname@example.org.