Google

Friday, June 23, 2006

Leverage the C# Preprocessor

Leverage the C# Preprocessor: "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 "