Conditional Compilation with Precompiler Directives in C#

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.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434

One Comment to “Conditional Compilation with Precompiler Directives in C#”

Comments are closed.