The VB.Net compiler directives give instructions to the compiler to preprocess the information before the actual compilation starts.
#
, and only white-space characters may appear before a directive on a line.In VB.Net, the following types of directives are available.
#Const
DirectiveThe #Const
directive defines conditional compiler constants, and these constants are always private to the file in which they appear.
#Const
directive./define
compiler option.expression
.The following code uses the #Const
directive.
#Const MyLocation = "USA"
#Const Version = 10.0
Sub ConstDirective()
#If Version > 9.0 Then
Console.WriteLine("Latest version installed")
#Else
Console.WriteLine("Latest version not installed")
#End If
End Sub
You can use constants defined with the #Const keyword only for conditional compilation. Constants can also be undefined, in which case they have a value of Nothing.
#ExternalSource
DirectiveThe #ExternalSource` Directive indicates a mapping between specific lines of source code and text external to the source.
The following code uses the #ExternalSource
directive.
Sub ExternalSourceDirective()
#ExternalSource ("c:\vbprogs\directives.vb", 5)
Console.WriteLine("This is External Code. ")
#End ExternalSource
End Sub
External source directives do not affect a compilation and cannot be nested. They are intended for internal use by the application only.
#If...Then...#Else
DirectiveThe #If...Then...#Else
directive conditionally compiles selected blocks of Visual Basic code. The behavior of the #If...Then...#Else
directives appears the same as that of the If...Then...Else
statements. However, the #If...Then...#Else
directives evaluate at compile-time, whereas the If...Then...Else
statements evaluate conditions at run time.
The following code uses the #If...Then...#Else
directive.
#Const MyLocation = "USA"
#Const Version = 10.0
Sub ConstDirective()
#If Version > 9.0 Then
Console.WriteLine("Latest version installed")
#Else
Console.WriteLine("Latest version not installed")
#End If
End Sub
#Region
DirectiveThe #Region
directive collapses and hides sections of code in Visual Basic files.
#Region
directive to specify a block of code to expand or collapse when using the Visual Studio Code Editor's outlining feature.The following code uses the #Region
directive.
#Region "MathFunctions" ' Insert code for the Math functions here. #End Region