C# preprocessor directives allow developers to influence the compilation process. These commands provide instructions to the compiler, enabling features like conditional compilation, code folding, and custom diagnostic messaging.
Summary of Directives
| Directive | Purpose |
|---|---|
#define |
Creates a symbol for conditional compilation. |
#undef |
Removes a defined symbol. |
#if |
Evaluates if a symbol is currently defined. |
#else |
Provides an alternative path for #if. |
#elif |
Combines #else and #if for multiple conditions. |
#endif |
Terminates a conditional block. |
#line |
Modifies the line numbers and filenames reported during errors. |
#error |
Triggers a compilation error at a specific point. |
#warning |
Triggers a compilation warning at a specific point. |
#region |
Defines a expandable/collapsible section in the IDE. |
#endregion |
Ends a #region block. |
Defining and Undefining Symbols
Directives such as #define and #undef must be placed at the very top of the source file, preceding all using statements and namespaces. Defining a symbol allows it to be checked via conditional logic.
#define ENABLE_FEATURE
using System;
namespace AppNamespace
{
class Program
{
static void Main()
{
#if ENABLE_FEATURE
Console.WriteLine("Feature enabled.");
#else
Console.WriteLine("Feature disabled.");
#endif
}
}
}
Conditional Logic
Preprocessing blocks support standard logical operators like &&, ||, !, ==, and !=. These directives are evaluated before the actual code execution, meaning the compiler only includes the code within a successful block in the final binary.
#define BETA_MODE
#if BETA_MODE && !RELEASE_MODE
// This code block is included only if BETA_MODE is set
#endif
Diagnostics: Errors and Warnings
#error and #warning are useful for enforcing build rules. #error halts the compilation process, while #warning produces a diagnostic message during the build without stopping it.
#define PRODUCTION
#if PRODUCTION
#warning Deploying to production environment.
#else
#error Configuration not allowed for deployment.
#endif
Code Organization
#region and #endregion do not affect the compilation of the binary, but they significantly improve code readability in IDEs by allowing developers to collapse or expand large segments of logic.
#region Data Access Layer
public void SaveData()
{
// Implementation details
}
#endregion