In this post we will see what are C# preprocessor directives, and what is their purpose.
C# preprocessor directives are a salient feature that allows you to conditionally include, exclude, or organize code before compilation.
Preprocessor directives are instructions processed by the C# compiler before actual compilation. They all begin with the # character. Their key characteristic is that they have no effect at runtime; they simply determine which code gets compiled and which does not.
Main points of Preprocessor directives:
- They provide instruction code to compiler before compilation process.
- Based on the instruction/directive, a piece of code can be excluded or included for compilation
- All directives begin with the # character.
- They have no effect at runtime; they simply determine which code gets compiled and which does not.
There are different C# preprocessor directives which are used for different purposes. Some of them are tabulated below:
| Directive | Meaning |
|---|---|
| #define | Defines a compilation symbol that can be used in conditional compilation. |
| #undef | Undefines a previously defined symbol. |
| #if | Compiles code only if a specified symbol or expression evaluates to true. |
| #elif | Specifies an alternative condition after an #if or another #elif. |
| #else | Specifies code to compile when preceding #if or #elif conditions are false. |
| #endif | Marks the end of an #if, #elif, or #else block. |
| #warning | Generates a custom compiler warning message. |
| #error | Generates a custom compiler error and stops compilation. |
| #line | Changes the compiler's line-number and file-name information for error reporting and debugging. |
| #region | Defines a collapsible code region in IDEs such as Visual Studio. |
| #endregion | Marks the end of a #region block. |
| #pragma | Controls compiler behavior, such as enabling or disabling specific warnings. |
| #nullable | Controls nullable reference type annotations and warnings. |
#define and #undef — Defining symbols
These preprocessor directives define or remove a symbol. These symbols are used anywhere in the code to check conditions. A directives symbol does not have a value; it simply either exists or it doesn't.
EXAMPLE 1
#define DEBUG_MODE
#define PREMIUM_USER
class Program
{
static void Main()
{
#if DEBUG_MODE
Console.WriteLine("Debug: Application starting...");
#endif
#undef PREMIUM_USER // symbol removed
#if PREMIUM_USER
Console.WriteLine("Premium features"); // it will not execute
#endif
}
}
Preprocessor directives (#define and #undef) are always written at the top of the file, before any using statements. In Real-world,
| DIRECTIVE | USAGE |
| #if DEBUG | debug-only logging |
| #if WINDOWS | platform-specific code |
| #pragma warning disable | legacy code warnings |
| #nullable enable | to write modern null-safe code. |
No comments:
Post a Comment