Use preprocessor directives in C#

C# actually doesn't have a true preprocessor but it treats these statements as if it did have one. These statements tell C# about how to process pieces of code. The directives are:

#if
Tests a Boolean value at compile time. If the value is false, then the code that follows is not compiled. In fact, the code isn't even examined so it could contain syntax errors and the program could still compile.
#else
Ends an #if block and starts a new block of code. If the #if condition is false, then this block of code is compiled.
#elif
Ends an #if block and tests a new Boolean condition.
#endif
Ends an #if ... #elif ... #else ... #endif series.
#define
Defines a compile-time constant to be true. You can use the constant with an #if or #elif test.
#undef
Undefines a compile-time constant.
#warning
Generates a warning and adds it to the compiler's output.
#error
Generates an error and adds it to the compiler's output.
#line
Modifies the compiler's line number.
#region
Starts a region that you can expand and collapse. This lets you easily group related pieces of code (for example, methods in a class) so you can collapse them in a group.
#endregion
Ends a region.

The #define directive must come at the top of the file. You can also define a symbol with the /define compiler option.

A third way to define a symbol is to open the Project menu, selecting Properties (at the bottom), selecting the Build tab, and entering the values you want to define in the Conditional Compilation Symbols text box. If you use this method, then the symbol is defined in all of the project's files.

One of the most common uses for preprocessor directives is to perform different tasks depending on values. The following code includes a different MessageBox.Show statement depending on which of the debug level values are defined (if any).

#if DEBUG_LEVEL_1
MessageBox.Show("Debug level 1");
#elif DEBUG_LEVEL_2
MessageBox.Show("Debug level 2");
#else
MessageBox.Show("Debug level 3");
#endif

Remember that any code that is not included is not even examined by the compiler so it may contain bugs. Also note that the result is similar to what you get using a normal if-else statement except the code that is included is selected at compile time not at run time.

The example program uses a series of #if ... #elfif ... #else ... #endif directives.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.