Home
Search
C# Define and Undef DirectivesUse the #define and #undef preprocessor directives and test the defined constants.
Define, undef. The #define and #undef directives influence compilation. We can test the symbols we define to add or remove code from being compiled.
Compilation info. These directives adjust compilation options for the entire file. As directives, they have no affect on runtime performance.
Directives
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.
Undef 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.
If The #if directive is evaluated at preprocessing time. It works in a similar way as the if-statement in the C# language itself.
If, Elif, Endif
Elif, 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.
// 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.
Using System
A summary. We demonstrated the #define and #undef preprocessing directives. These provide a way to conditionally compile or remove parts of the source text.
Home
© 2007-2022 sam allen.
see site info on the changelog.