C# if/then directives for debug vs release
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.