Conditional compilation

F

FireStarter

Guys, in the code that follows, why does the method F() still compile, even if
DBG is undefined? Inside method G(), the code inside <#if DBG> does not compile
(notice that I can write whatever I want in there, I will not receive a
compilation error). I do get such an error in F() - because of the garbage I
intentionally put there - but F() should not compile in the first place.
Am I misusing this [Conditional...] attribute?!



#undef DBG
using System.Diagnostics;
class Class1 {

public Class1() {
int y = 0;
}

public void G() {

int x = 0;
x++;
#if DBG
// garbage here, that does not generate
// compilation errors - correct
x*&$%bbb
#endif
}

[Conditional("DBG")]
public void F() {
// garbage here, that generates compilation errors,
// although this is a conditional method, and DBG is undefined
x*&$%bbb
}
}
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

I think that it depend in which pass the different elements are parsed.

I'm not 100% sure of the next as my experience with the compilation process
is not that deep but it's valid in the "old" C world

the #undef DBG is a preprocessor directive , it's handle before the code
really reach a semantic or syntax parse, this is the first step to compile
the source code, this preprocesor get rid of the part that will not be
compiled therefore the compiler never sees the gargabe you write in this
part:
#if DBG
// garbage here, that does not generate
// compilation errors - correct
x*&$%bbb
#endif

Now if you use [Conditional("DBG")] this is not a preprocessor directive and
therefore it leave it there for the compiler to see, when it does reach the
compiler and it start doing the syntax parsing ( I think remember it's done
first than the semantic ) it see the wrong code and report it as error.

This must be more or less the process.

Hope this help,
 
W

William Ryan

Conditional code does get compiled with your project so it's got to be
valid. For instance, if you used two functions with the same name and
signature, marked one with Debug and the other with Release, you could
compile because there would be a conflict. My point being that it does get
compiled in.

As an aside, instead of using DBG which you set, why not use "DEBUG", then
when you switch the build mode to release, it's automatically handled
instead of you have to go into properties and include directives? Just a
suggestion.

HTH,

Bill
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top