Search code examples
c#debuggingc-preprocessorcompiler-directives

Omitting code: Any difference between Conditional Attribute and pre-processing directive?


I am wondering what the difference is between

#define MYSYMBOL

#if MYSYMBOL
public void foo () {

    // ...
}
#endif

and

#define MYSYMBOL

[Conditional("MYSYMBOL")]
public void foo () {

    // ...
}

?

Maybe it's obvious but if someone could give me a hint in the right direction I would be thankful :)


Solution

  • They are different.

    Using #if removes the enclosed code altogether, so any code that calls the method won't compile because the method has disappeared. You can also wrap any amount of code this way, not just a single whole method.

    Using [Conditional] means the method won't be called at runtime, but calls to it will still compile ( but the calls will not be emitted in the IL code ). Also, this way, the method must return void and not have any out or ref parameters.