views:

842

answers:

5

In Solution properties, I have Configuration set to "release" for my one and only project.

At the beginning of the main routine, I have this code, and it is showing "Mode=Debug". I also have these two lines at the very top:

#define DEBUG 
#define RELEASE

Am I testing the right variable?

#if (DEBUG)
            Console.WriteLine("Mode=Debug"); 
#elif (RELEASE)
            Console.WriteLine("Mode=Release"); 
#endif

My goal is to set different defaults for variables based on debug vs release mode.

Thanks,

Neal Walters

+2  A: 

If you are trying to use the variable defined for the build type you should remove the two lines ...

#define DEBUG  
#define RELEASE 

... these will cause the #if (DEBUG) to always be true.

Also there isn't a default Conditional compilation symbol for RELEASE. If you want to define one go to the project properties, click on the Build tab and then add RELEASE to the Conditional compilation symbols text box under the General heading.

The other option would be to do this...

#if DEBUG
    Console.WriteLine("Debug");
#else
    Console.WriteLine("Release");
#endif
Matthew Whited
+5  A: 

By default, Visual Studio defines DEBUG if project is compiled in Debug mode and doesn't define it if it's in Release mode. RELEASE is not defined in Release mode by default. Use something like this:

#if DEBUG
  // debug stuff goes here
#else
  // release stuff goes here
#endif

If you want to do something only in release mode:

#if !DEBUG
  // release...
#endif

Also, it's worth pointing out that you can use [Conditional("DEBUG")] attribute on methods that return void to have them only executed if a certain symbol is defined. The compiler would remove all calls to those methods if the symbol is not defined:

[Conditional("DEBUG")]
void PrintLog() {
    Console.WriteLine("Debug info");
}

void Test() {
    PrintLog();
}
Mehrdad Afshari
+10  A: 

Remove the #define DEBUG in your code. Set preprocessors in the build configuration for that specific build (DEBUG/_DEBUG should be defined in VS already).

The reason it prints "Mode=Debug" is because of your #define and then skips the elif.

Also, the right way to check is:

#if DEBUG
    Console.WriteLine("Mode=Debug"); 
#else
    Console.WriteLine("Mode=Release"); 
#endif

Don't check for RELEASE

psychotik
+1  A: 

Remove your defines at the top

#if DEBUG
        Console.WriteLine("Mode=Debug"); 
#else
        Console.WriteLine("Mode=Release"); 
#endif
McAden
+1  A: 

I prefer checking it like this vs looking for #defines:

if (System.Diagnostics.Debugger.IsAttached)
{
   //...
}
else
{
   //...
}

With the caveat that of course you could compile and deploy something in debug mode but still not have the debugger attached.

Joel Coehoorn