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. Directives add a layer of compile-time logic to VB.NET programs. They can make programs harder to read.

Const, If. This program uses the #Const directive to set the SPECIAL symbol to the value 1. Inside the Main Sub, we use an #If directive to test the value of SPECIAL.

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.

Info: 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

A discussion. Preprocessing directives are handled at an early stage of compilation. The preprocessor scans VB.NET programs before compiling code statements into intermediate language.

Info: Directives are separate from the rest of the VB.NET code. 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.

A summary. Directives add another layer of compilation to VB.NET programs. With #If, #Const and even #Region, we access another set of abilities in this language.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to