VB Quark #2: compiler directives and constants

Posted Sat, Sep 24 2011 15:31 by bill

Building upon VB Quark #1 , did you know you can use compiler directives alongside expressions in constants ?

#If CONFIG = "Debug" Then
   Const path As String = "Z:\mydebug.sdf"
#Else
   Const path As String = "|DataDirectory|\Database1.sdf"
#End If

   Const connectionString = "Data Source=" & path

The nice thing about this is as you change the config from Debug to Release, Visual Studio will grey out the parts that aren’t in the current compilation. In the above example, when I do a debug build I’m using my database in Z:\mydebug.sdf, but when I do a release build it automatically uses the database Database1.sdf in the application’s DataDirectory.

You can use compiler directives pretty much anywhere in your code to replace any code block with another at compile time based on the directives.