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()
Console.WriteLine(“DEBUG symbol is defined!”);
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.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s