C# Preprocessor directives are commands for the compiler so they affect the build process.Since they affect the build process so they are useful in several common scenarios.Here we will look into some of the Conditional Preprocessor directives in C#.Conditional Preprocessor directives are used to include or exclude portions of code in the build.
When writing code we often want to execute some code only in the development environment but not in the release build of the application.One commonly used way to disable the code from executing in the development environment and enable the code in the release build is to comment out the code in the development environment and then uncomment while deploying.
The problem with this method is that we can forget to uncomment the code.If we are commenting the code at lots of places then it is very likely to forget to uncomment the code.Also we sometimes need to build the code differently for different platforms.The solution to the mentioned scenarios is using the compilation symbols.
For example it is a common requirement to compile certain portions of the code while debugging.Visual studio by default creates DEBUG compilation symbol only in the debug configuration.
//Code to execute only in the debug configuration
Similarly if we want to execute certain code only in the release build we can use the following
//Code to execute only in the release configuration
#if and #endif
These are the preprocessor directives for selectively executing the code.So if we have a requirement for two separate versions of a code then instead of creating two different code bases or copies we can use the #if and #endif directives so that the code is executed only when a certain condition is met.
We can easily write code that will be executed only in the debug build as:
Console.WriteLine("Currently testing the application!");
Console.WriteLine("This code will not go to production.");
We may not realize the use of this directive by just looking at the above code but imagine if we are using the test code at hundreds of places then what pain it would be by manually going to each and every line where the test code is being used and then delete or uncomment the code.If we are selectively compiling the code as above then we just need to remove the compilation symbol and the code will not be included in the release build.
Defining the Compilation symbol
If we need more compilation symbols then the ones provided by Visual Studio by default ,such as DEBUG,then we are free to create new ones using the #define directive
There is a #define directive that is used to define the compilation symbol.
For example we can define a new compilation symbol called TEST as: