How to Use Preprocessor in C#


C# preprocessor is fundamentally very similar to C preprocessor. The preprocessor in C# starts with a ‘#’ symbol. Some of the terms or the directives that are used as preprocessors are as follows:
• #if
• #else
• #endif
• #define
• #undef
• #warning
• #error
The #if, #else and #endif are conditional directives and are used to decide on the parts of the program to be included or excluded. The #define and #undef are definition directives used to define terms and values. The #error and #warning are directives used to report errors and warnings.

Step 1: Implementation

The following example defines the term ‘TEST’ using the #define directive and the conditional directives are used to check for the definition to execute the set of statements required.

Code – Preprocessor

Step 2: Output

The #if directive in C# checks for the condition. Since TEST is defined, this returns a true value to the if directive. The statement inside the #if directive gets executed. This prints ‘TEST is defined’ on to the screen.

Output – preprocessor

Step 3 – The Undef Preprocessor

The #undef directive in C# can be used to undefined ‘TEST’. In this case, the statement below the #else directive gets printed.

Output - #undef preprocessor