13 Oct 2008

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:

  • Using a #define directive. Very easy to to add, but lacks in flexibility, as you will have to change the code itself when you want to build production code. Note that this statement has to be on the first line of the source code file.
  • By passing symbols to the compiler using the /define command line argument. This is much more flexible, as you can use the same code for debug and production code.

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.



blog comments powered by Disqus