C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: These directives can make your project simpler—and configurable with compile-time options.
Here: The #if DOT || NET block is omitted but the #elif PYTHONS block is allowed. The code inside the last directive is compiled.
define, undefInfo: The goal of this program is to demonstrate the #if, #elif, and #endif syntax. Please avoid #else if, #elseif, or #elsif—they won't work.
Tip: You can use the || and && operators within the conditions. You can negate a symbol, such as with !NET, and this inverts its Boolean value.
C# program that uses if, conditional compilation
#define PERLS
#define PYTHONS
#define NET
#undef NET
using System;
class Program
{
static void Main()
{
#if PERLS
Console.WriteLine("PERLS"); // Compiled.
#endif
#if DOT || NET
Console.WriteLine("DOT OR NET"); // Skipped.
#elif PYTHONS
Console.WriteLine("PYTHONS"); // Compiled.
#endif
#if (PERLS || PYTHONS) && !NET
Console.WriteLine("PERLS OR PYTHONS"); // Compiled.
#endif
}
}
Output
PERLS
PYTHONS
PERLS OR PYTHONS
Tip: This is useful when developing if you are making significant changes to aspects of your code base.
Note: As an aside, #if true is supported, but it is only useful if you are going to change the directive into something more significant.
C# program that uses if, false
class Program
{
static void Main()
{
/*
*
* This is valid C# code.
*
* */
#if false
void a = 100 * whatever;
#endif
}
}
C# program that uses else directive
using System;
class Program
{
static void Main()
{
#if false
Console.WriteLine(0);
#else
Console.WriteLine(1);
#endif
}
}
Output
1
Then: Click on Build: this presents the "Conditional compilation symbols" textbox. Type the symbols, separated by spaces, and recompile.