Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional("Debug") + #if DEBUG

Tags:

c#

.net

vb.net

I have seen in Debugging .net 2.0 Applications the following code

[Conditional("DEBUG")]
void AssertTableExists() {
    #if DEBUG
        ...
    #endif
}

Is there any reason to use the #if directive? I mean, from what I understand the method will only be called if the DEBUG is defined, so I don't see a point in having the #if in the method body.

like image 668
devoured elysium Avatar asked Sep 20 '09 23:09

devoured elysium


1 Answers

Coincidentally I just happened to answer your question on my blog last week.

http://ericlippert.com/2009/09/10/whats-the-difference-between-conditional-compilation-and-the-conditional-attribute/

The #if directive is necessary if the body of the method refers to entities which are themselves declared under #if DEBUG directives. For example

#if DEBUG
static private int testCounter = 1;
#endif

[Conditional("DEBUG")] void CheckConsistency()
{
#if DEBUG
  testCounter++;
#endif
...

That would not compile in the release build if you omitted the #if DEBUG in the method body.

like image 161
Eric Lippert Avatar answered Oct 05 '22 07:10

Eric Lippert