C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: The undef directive is the opposite of the define directive. It doesn't matter if the symbol was never defined in the first place.
Undef: In the code, the #undef B cancels out the #define B directive, leaving B not defined.
If: The #if directive is evaluated as preprocessing time, not runtime. It works in a similar way as the if-statement in the C# language itself.
If, Elif, EndifElif, Else: The #elif directive is the same as #if, except it must follow an #if or other #elif. The #else directive is the default case.
Endif: The #endif directive serves to terminate the #if #elif or #if #else directive structures.
C# program that define and undef directives
// Define B, then define A.
// ... You can use undef at the top here too.
// ... Try changing A to C.
#define B
#define A
#undef B
using System;
class Program
{
static void Main()
{
// Use an if/elif/endif construct.
#if A
Console.WriteLine("a");
#elif B
Console.WriteLine("b");
#elif C
Console.WriteLine("c");
#endif
// Use an if/else/endif construct.
#if A
Console.WriteLine("a2");
#else
Console.WriteLine("!a2");
#endif
}
}
Output
a
a2
Tip: Instead of reading the language specification, you can just experiment in the compiler to see what works.
Info: In the C# language, the "using System" line is also a directive, but not a preprocessing directive.
Using SystemNote: Please see section 9.5 of the ECMA-344 "C# Language Specification", "Pre-processing directives" for a complete reference.