tags:

views:

184

answers:

2

I am just wondering if these code blocks gets compiled into .dll

I don't think this one gets compiled at all

#if SOMETHING_UNDEFINED
// some code - this is ignored by the compiler
#endif

Now what about these?

1.

if(false) {
  // some code - is this compiled?
}

2.

const bool F = false;
if(F) {
  // some code - is this compiled?
}

3.

bool F = false;
if(F) {
  // some code - is this compiled?
}

EDIT: Sorry, I was talking about Visual Studio

+7  A: 

Just testing it, the Microsoft C# 4 compiler doesn't, and it looks like the Mono gmcs compiler version 2.4.0.0 doesn't either. I don't know that there's anything in the spec prohibiting it though.

EDIT: When I answered this, only the first version was present. Case 2 is equivalent to case 1, but case 3 isn't.

Jon Skeet
for all three cases?
Justin
No, that last case is compiled into the assembly.
Lasse V. Karlsen
Thank you. I guess it doesn't matter if the constant is in another class or even another project (in Visual Studio), does it?
@aximili: I would expect it to be anything that the C# compiler deems a constant expression, which could be a const from another assembly.
Jon Skeet
+1  A: 

Just an addendum to the answer:

The reason is I beleive, that it'll only do static checking. in the first case if(false) it'll see that that's unreachable code by a simple pattern check, so it'll not compile it in (should give a warning too).

For the second case, because F is a constant and it know it never changes,when doing static checking it can just do substitution. [F->false]<< body >>. and that would give the same code as the first one.

The last one is tricky. Since it's infeasible to know that 100% using static checking only what the value of F is. C# like all imperative languages have side effects.

imagine if you rewrite the code slightly

bool F = false; 
foo(ref F);
if(F) { 
  // some code - is this compiled? 
} 

The problem here is, it doesn't know what foo does to F. in order to find out, it would have to trace (and possibly evaluate) the function, now imagine a very large programs with alot of these patterns, after all, If statements are used alot, trying to find the runtime value of F for all these statements would be very slow and time consuming and sometimes not even possible.

Phyx