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.
#if DEBUG_LEVEL_1Remember 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.
MessageBox.Show("Debug level 1");
#elif DEBUG_LEVEL_2
MessageBox.Show("Debug level 2");
#else
MessageBox.Show("Debug level 3");
#endif


Comments