- Posted by Shay Friedman on October 15, 2009
There are times when we need to use different code statements for different build configurations – this means that some code will not exist in assemblies that are built in certain build configurations.
Compilation symbols come to help in this case. You can set a symbol that will exist in a specific build configuration and then use it inside your code files to write or exclude code when this project is built using this build configuration.
The most familiar case of this scenario is debug and release build configurations. Actually, the debug build configurations comes with a compilation symbol by default named DEBUG. By using it you can write code that will run only when you compile your project in debug mode (show extra message boxes, write more logs, etc.).
Creating Compilation Symbols
- In Visual Studio, go to Project-> <project name> Properties…
- The project properties view will open. Click on “Build” on the left.
- The Build settings will open on the right. The first field there, with the label “Conditional compilation symbols” is the one you need.
- Add there the name or names (semi-colon separated) of the compilation symbols you want to define. Pay attention that the naming convention for these symbols is all uppercase.
You’re done. You can start using the compilation symbols you have just defined. The next screenshot contains a sample project with two symbols defined – SHAY and FRIEDMAN:
Using Compilation Symbols
In order to use the compilation symbols you have defined, you need to use the special compilation conditions. If these conditions are not met, the code within the condition will not be compiled at all.
The condition starts with #if <condition> and ends with #endif. For example, the next code will be compiled only when SHAY is defined (which is in debug build configuration):
Console.WriteLine("SHAY is defined! woot!");
You can also write more complicated conditions like !SHAY for all build configuration without SHAY defined. You can add conditions too – SHAY && FRIEDMAN.
Well, that’s about it!
Hope it helps,