C# Preprocessor #if directive

I only discovered lately that C# compiler had a preprocessor directives. The only one I knew was the #region and #endregion, which is only used for aesthetical reasons in Visual Studio.

The one that I was particularly interested in was the #if and #endif. When the compiler encounters a #if [symbol] statement (followed eventually by an #endif statement), the compiler will compile the surrounded code only if the symbol is defined.

Conditional (#if) directive

Let’s take a small command line example:

using System;
using System.Collections.Generic;
using System.Text;

namespace PreprocessorTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello,");

#if DEBUG
            Console.WriteLine("This is a debug line");
#endif

            Console.WriteLine("Goodbye.");

            Console.ReadLine();
        }
    }
}

This code, when ran, will only execute the second Console.WriteLine statement only if the DEBUG symbol is defined.

For obvious reasons, this is very useful. You can include debug code in the application and let the compiler sort what has to be included when you compile. This leads us to an important point: how is a symbol defined?

Symbol definition

There are two ways to define a symbol:

One last thing that is quite interesting. Visual Studio automatically defines DEBUG and TRACE symbols in Debug configuration, while it only defines TRACE symbol in Release configuration. This can, however, be changed by going in the project properties page, in the Debug section:

Visual Studio Project properties Build section

So, by default, using the DEBUG symbol means that the surrounded code will be compiled in Debug mode, but ignored in Release mode.

Comments

Leave a Reply