Conditional Compilation with Precompiler Directives in C#

By | October 8, 2013

Coming from C or C++, C# has always the flexibility to handle directives. The directives are well known in those languages, but most of the developers don’t know that these things still exists in C#. There are few pre-processor directives available on C# which help you to define a constant which is replaced during compile time, or even put some logic to the compiler to compile a specific portion of code depending on some logic.

For instance, let us look the code below :

#if DEBUG
#warning You should not compile in debug mode, use release mode
#endif

The DEBUG is a preprocessor variable which is defined when the program is compiled in debug mode. So when the compilation took place, if the compilation is in debug mode, placing the line will put a warning on the Error console saying “You should not compile in debug mode, use release mode.

Similarly, you can use #error directive to create an error on the console based on certain values.

#define ABHISHEK
class Program
{
static void Main(string[] args)
{
#if(ABHISHEK)
{
Console.WriteLine("Inside Abhishek Block");
}
#else
{
Console.WriteLine("Inside other block");
}
#endif
}
}

Here if you compile the code with ABHISHEK defined, it will compile the portion of the code which has #if(ABHISHEK)

Try looking into this in Reflector, you will see the portion inside #Else block is even not compiled and there is no IL corresponding to that.

There are lot of other directives that comes handy at times. We will cover them later with examples. Stay tune.

Happy programming.

One thought on “Conditional Compilation with Precompiler Directives in C#

  1. Pingback: Blog Posts of the Week (6th - 12th October 2013) - The South Asia MVP Blog - Site Home - TechNet Blogs

Comments are closed.