In C#, the #else
directive is used in conjunction with the #if
directive to define an alternative block of code that should be compiled if the condition specified in the #if
directive evaluates to false. It is part of the conditional compilation feature in C#.
Here’s an example to illustrate its usage:
#define DEBUG using System; class Program { static void Main() { #if DEBUG Console.WriteLine("Debug mode is enabled."); #else Console.WriteLine("Debug mode is disabled."); #endif // Rest of the code... } }
In the above code, the #if DEBUG
directive checks if the symbol DEBUG
is defined. If it is defined, the code inside the #if
block is compiled. Otherwise, the code inside the #else
block is compiled.
In this case, assuming the DEBUG
symbol is defined, the output would be: “Debug mode is enabled.” If the DEBUG
symbol is not defined, the output would be: “Debug mode is disabled.”
The #else
directive provides a way to handle different compilation scenarios based on the defined symbols, allowing you to have alternative code paths depending on certain conditions during compilation.