Conditional compilation is being able to tell the compiler to only compile certain areas of code if some conditions are met. For example, you have probably noticed that Visual Studio sets up 2 different compilation profiles with each project – Debug and Release. The Debug profile has a constant enabled called DEBUG. You can find this by going into My Project, Compile tab, and clicking on the “Advanced Compile Options” button. There is a section there called “Compilation Constants”. There are a couple of pre-defined ones with checkboxes – DEBUG and TRACE. You can toggle these on and off. You can also add your own custom constants. Another way of defining constants is using #Const in a code file.
These constants are used by the compiler – they aren’t like normal constants. That means that you can create different modes of compilation. Eg. if you are producing an application which is available in 2 different editions (“Home” and “Professional” for example), you may wish to define #Const EDITION = “Home”. You can create separate compiler profiles for this as well, so you can have Home Debug, Home Release, Pro Debug and Pro Release.
Once you’ve got a compiler constant, you can use it to decide whether some code is compiled or not. This is done using #If.
For example,
#If EDITION=”Home”
‘home code
#Else
‘pro code
#End If
The important thing here is that when you compile in Pro mode, the home code never actually makes it into the compiled assembly at all – it isn’t just that it is never executed. This means that your assembly is smaller, and there is no way of hacking around it to get the code to work, because it just isn’t there (unless you hack it in). Also, when you switch Visual Studio to use a different compilation profile or change the constants around, it effectively treats the code that is within the blocks that are not to be compiled for the current profile as though they were just like comments.
Visual Studio pre-defines some useful compiler constants which you can use as well…
CONFIG is the name of the configuration (Debug/Release by default)
DEBUG is whether we are compiling in debug mode or not
PLATFORM is the CPU platform we are targeting (eg. x86, x64)
TARGET is the assembly type (eg. winexe)
TRACE is whether debug tracing is enabled
VBC_VER is the version number of the VB compiler (I assume C# has some equivalent like CS_VER)
_MyType – I’m not sure exactly what this is – I think it is the type of application that you are compiling so that the compiler knows what structure to use for the My. namespace.
- .NET Compilation Part 1: Profiles
- .NET Compilation Part 2: Conditional Compilation











