C# if/then directives for debug vs release

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.


DEBUG/_DEBUG should be defined in VS already.

Remove the #define DEBUG in your code. Set preprocessors in the build configuration for that specific build.

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

The right way to check is:

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

Don't check for RELEASE.


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();
}

I prefer checking it like this over looking for #define directives:

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.