Reputation: 6280
Sometimes I find that preprocessor directives aren't flexible enough for my application, so I've been wondering if it is possible to exchange the #if
functionality of the preprocessor.
Example:
const bool Debug = false;
if (Debug)
{
...
}
Will the if statement and its content be removed by the compiler? Alternatively, if a the Debug
constant's value is true
, will the compiler remove the condition check and keep the contents in place?
Upvotes: 2
Views: 2708
Reputation: 660463
Will the if statement and its content be removed by the compiler? Alternatively, if a the Debug constant's value is true, will the compiler remove the condition check and keep the contents in place?
Yes, and yes. However, those are implementation details, not guarantees of the language.
Some interesting aspects of using if(false)
to control conditional compilation:
The compilation is not conditional at all; the body of the if
will be compiled just like any other code. If it contains syntax errors, you'll get syntax errors. If it contains overload resolution errors, you'll get overload resolution errors. "Go to usage" and other IDE features continue to work.
This is very different from controlling with #if false
; text that is omitted because of the preprocessor is treated as comments. "Go to usage" will not find a usage that is conditionally compiled out, you don't get syntax colouring, and so on. However, the code can be completely broken because, after all, it is basically just a comment.
However, the first point is a slight lie; there is one difference. Code inside if(false)
is not checked for definite assignment errors:
int x;
if (false)
Console.WriteLine(x); // no error!
Because after all, there is no way that x is going to be read before it is written in this program fragment!
Upvotes: 13
Reputation: 1039408
Will the if statement and its content be removed by the compiler?
Yes, the if
statement will be removed from the resulting IL even if you compile in Debug mode.
Alternatively, if a the Debug constant's value is true, will the compiler remove the condition check and keep the contents in place?
Yes, and this will happen even in if you compile in Debug mode.
For example:
static void Main()
{
const bool Debug = false;
if (Debug)
{
Console.WriteLine("ok");
}
}
results in the following IL:
.method private hidebysig static void Main() cil managed
{
.entrypoint
.maxstack 8
L_0000: ret
}
As you can see the entire body of the method is removed from the IL
and:
static void Main()
{
const bool Debug = true;
if (Debug)
{
Console.WriteLine("ok");
}
}
results in:
.method private hidebysig static void Main() cil managed
{
.entrypoint
.maxstack 8
L_0000: ldstr "ok"
L_0005: call void [mscorlib]System.Console::WriteLine(string)
L_000a: ret
}
Here the Console.WriteLine is always executed without performing any if
.
Upvotes: 3