In C#, the #undef
directive is used to undefine a previously defined symbol or macro. It is typically used in conjunction with the #define
directive, which is used to define symbols that can be used for conditional compilation.
Here’s an example to illustrate the usage of #undef
:
#define DEBUG // Define the DEBUG symbol #if DEBUG Console.WriteLine("Debugging is enabled."); #else Console.WriteLine("Debugging is disabled."); #endif #undef DEBUG // Undefine the DEBUG symbol #if DEBUG Console.WriteLine("Debugging is enabled."); #else Console.WriteLine("Debugging is disabled."); #endif
In this example, the #define
directive defines the DEBUG
symbol, which is used for conditional compilation. When the DEBUG
symbol is defined, the code within the #if DEBUG
block is included during compilation.
Afterward, the #undef
directive is used to undefine the DEBUG
symbol. As a result, when the #if DEBUG
block is encountered again, the code within the #else
block is included during compilation because the DEBUG
symbol is no longer defined.
The output of the above example would be:
Debugging is enabled. Debugging is disabled.
The #undef
directive is primarily used in scenarios where conditional compilation is required based on the presence or absence of certain symbols. By undefining a symbol, you can change the compilation behavior of your code.