Example. Here we define the symbol B, then the symbol A, then undefine the symbol B. The program will compile with A being defined, and B being undefined.
Detail In the code, the #undef B cancels out the #define B directive, leaving B not defined.
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.
Detail The #if directive is evaluated at preprocessing time. It works in a similar way as the if-statement in the C# language itself.
Detail The #elif directive is the same as #if, except it must follow an #if or other #elif. The #else directive is the default case.
Detail The #endif directive serves to terminate the #if #elif or #if #else directive structures.
// 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
}
}a
a2
Symbol syntax. There are some invalid syntaxes for defined symbols. You cannot use a number value as the defined identifier, for example.
Tip Instead of reading the language specification, you can just experiment in the compiler to see what works.
Directives. These are evaluated at preprocessing time. Directives provide hints about how the program is compiled, not what it does with instructions and the evaluation stack.
Info In the C# language, the "using System" line is also a directive, but not a preprocessing directive.
A summary. We demonstrated the #define and #undef preprocessing directives. These provide a way to conditionally compile or remove parts of the source text.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 26, 2022 (grammar).