Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use #if..#elif...#else...#endif directives in C#?
Preprocessor directives in C# begin with # and are processed before compilation. The #if..#elif...#else...#endif directives allow conditional compilation, meaning you can include or exclude code blocks based on defined symbols.
These directives are useful for creating debug builds, platform-specific code, or feature toggles without affecting runtime performance.
Syntax
Following is the syntax for conditional compilation directives −
#if condition // code block 1 #elif condition // code block 2 #else // code block 3 #endif
Key Directives
-
#if− Tests if a symbol evaluates to true -
#elif− Allows multiple conditional branches (else-if) -
#else− Executed when all previous conditions are false -
#endif− Marks the end of the conditional block
Using #if with Single Symbol
Example
#define DEBUG
using System;
class Program {
static void Main(string[] args) {
Console.WriteLine("Application started");
#if DEBUG
Console.WriteLine("Debug mode is ON");
#endif
Console.WriteLine("Application finished");
}
}
The output of the above code is −
Application started Debug mode is ON Application finished
Using #if..#elif..#else..#endif
Example
#define RELEASE
#undef DEBUG
using System;
class Program {
static void Main(string[] args) {
#if DEBUG
Console.WriteLine("Debug version");
#elif RELEASE
Console.WriteLine("Release version");
#else
Console.WriteLine("Unknown version");
#endif
Console.WriteLine("Program executed successfully");
}
}
The output of the above code is −
Release version Program executed successfully
Using Multiple Conditions with Logical Operators
Example
#define WINDOWS
#define X64
using System;
class Program {
static void Main(string[] args) {
#if (WINDOWS && X64)
Console.WriteLine("Windows 64-bit platform");
#elif (WINDOWS && !X64)
Console.WriteLine("Windows 32-bit platform");
#elif (!WINDOWS && X64)
Console.WriteLine("Non-Windows 64-bit platform");
#else
Console.WriteLine("Non-Windows 32-bit platform");
#endif
}
}
The output of the above code is −
Windows 64-bit platform
Common Use Cases
| Use Case | Example Symbol | Purpose |
|---|---|---|
| Debug vs Release builds |
DEBUG, RELEASE
|
Include debug statements or optimizations |
| Platform-specific code |
WINDOWS, LINUX
|
Conditional API calls or features |
| Feature toggles | BETA_FEATURE |
Enable/disable experimental features |
Conclusion
The #if..#elif..#else..#endif directives provide conditional compilation in C#, allowing you to include or exclude code blocks based on defined symbols. These directives are processed at compile-time and are essential for creating platform-specific builds, debug configurations, and feature toggles.
