Preprocessor Directives   



Preprocessor directives are processed before the source code is compiled. Like C++ the C# compiler supports a conditional compilation mechanism. These directives provide a means for us to prevent or enable the compilation of sepcific blocks of code 


 # define and #undef

The #define and #undef directives are used to define and undefine Preprocessor identifiers; we can use these to tell the preprocessor whether specific blocks of code are to be compiled, according to whether a particular identifier has been defined.

#define x
#undef y

where x and y are names. 


 # if

We can delimit code using the #if and #endif. The preprocessor # if mechanism can be used ato conditionally include or omit blocks of code:

#define x 

# if x

code

#endif


#elif and #else

These keywords make up the if ...else if...else mechanism:

#define x
# if x
code
#elif y
code 
#else
code

 


 nested #ifs

As we can nest the ifs , we can nest #ifs in the following way

#define x
#if x

#if y

code

#endif

#endif

We can also use logical operators with #if, the above code is equivalent to:

#define x
#if x && y

code

#endif 

Similarly we can use the !, ==, !=,&& and || operators with #if. 


#region and #endregion

These directives are used to mark blocks of code. These regions can be expanded and collapsed using VS.NET’s outlining feature. These can be used with comments for ease of other developers.


#warning and #error

If we want to flash a warning or raise an error at compile time we can use the # warning and #error directives.

#if x

#error x is not accessible.

#endif

#if y

#warning This may give wrong results.

#endif

Remember that #if x means that if x is #defined
 


#line

The #line directive can be used to alter the file name and line number information which is output by the compiler in warnings and error messages. 

Consider the program :

public static int Main(string[] args)
{

#line 100 "xyz.sc" 
#if x
#warning pseudo warning
#endif 
return 0;

}

Here the program flashes a warning “pseudo warning” , but at line 101 instead of what the real line is and the file name is changed to xyz.sc.