Mastering C# — Preprocessor Directives
2 min readAug 20, 2024
Preprocessor directives are commands in C# that are processed before the actual compilation of code begins. They instruct the compiler to perform specific pre-compilation tasks, such as conditional compilation, region organization, or including external resources. These directives begin with a #
symbol and do not require a semicolon (;
) at the end.
Common Preprocessor Directives in C#
1. #define
and #undef
#define
creates a symbolic constant for conditional compilation. Unlike constants in C#, these are not visible at runtime.#undef
removes a symbolic constant.
#define DEBUG
// Later in the code
#undef DEBUG
2. #if
, #else
, #elif
, and #endif
- These are used for conditional compilation. The compiler will only compile the code between these directives if the specified condition is true.
#define DEBUG
#if DEBUG
Console.WriteLine("Debug version");
#endif
3. #warning
and #error
#warning
allows you to generate a custom compiler warning.#error
generates a compiler error. Compilation stops if an#error
directive is reached
#warning This is a warning message
#error This is an error…