Leverage the C# Preprocessor

Leverage the C# Preprocessor

  • Comments 7

Like other languages in the C-family, C# supports a set of 'preprocessor' directives, most notably #define, #if and #endif (technically, csc.exe does not literally have a preprocessor as these symbols are resolved at the lexical analysis phase, but no need to split hairs…).

The #define directive allows you to set up custom symbols which control code compilation. Be very aware that unlike C(++), C#'s #define does not allow you to create macro-like code. Once a symbol is defined, the #if and #endif maybe used to test for said symbol. By way of a common example:

#define DEBUG
using System;

public class MyClass
{
  public static void Main()
  {
    #if DEBUG
      Console.WriteLine("DEBUG symbol is defined!");
    #endif
  }
}

When you use the #define directive, the symbol is only realized within the defining file. However if you wish to define project wide symbols, simply access your project's property page and navigate to the "Configuration Properties | Build" node and edit the "Conditional Compilation Constants" edit field. Finally, if you wish to disable a constant for a given file, you may make use of the #undef symbol.


Tip from Andrew Troelsen
Posted by: Duncan Mackenzie, MSDN
This post applies to Visual C# .NET 2002/2003/2005

Leave a Comment
  • Please add 3 and 1 and type the answer here:
  • Post
Page 1 of 1 (7 items)