CSharp/C# Tutorial - C# Preprocessor Directives

Preprocessor directives supply the compiler with additional information about regions of code.

The most common preprocessor directives are the conditional directives.

For example:

#define DEBUG//from   w  w  w .j  a  v  a2s  . c  o  m

class MyClass{
   int x;
   void OneMethod(){
       #if DEBUG
          Console.WriteLine ("Testing: x = {0}", x);

In the code above, OneMethod is compiled as conditionally dependent upon the presence of the DEBUG symbol.

If we remove the DEBUG symbol, the statement is not compiled.

Preprocessor symbols can be defined within a source file, and they can be passed to the compiler with the /define:symbol command-line option.

With the #if and #elif directives, we can use the ||, &&, and ! operators to perform or, and, and not operations on multiple symbols.

The following directive instructs the compiler to include the code that follows if the TESTMODE symbol is defined and the DEBUG symbol is not defined:


The #error and #warning symbols prevent accidental misuse of conditional directives.


The following table lists the preprocessor directives.

Preprocessor directiveAction
#define symbolDefines symbol
#undef symbolUndefines symbol
#if symbol[operator symbol2]...symbol to test operators are ==, !=, &&, and ||followed by #else,#elif, and #endif
#elseExecutes code to subsequent #endif
#elif symbol[operator symbol2]Combines #else branch and #if test
#endifEnds conditional directives
#warning textoutput warning text in compiler
#error textoutput error text in compiler
#pragma warning [disable | restore]Disables or restores compiler warning(s)
#line [number["file"] | hidden]number specifies the line in source code; file is the filename to appear in computer output;
#region nameMarks the beginning of an outline
#endregionEnds an outline region

Pragma Warning

To this effect, the compiler allows you to selectively suppress warnings with the #pragma warning directive.

In this example, we instruct the compiler not to warn us about the field Message not being used:

public class Foo{
   static void Main() { }
   #pragma warning disable 414
      static string Message = "Hello";
   #pragma warning restore 414

Omitting the number in the #pragma warning directive disables or restores all warning codes.

We can compile code with the /warnaserror to tell the compiler to treat any residual warnings as errors.