What is different between using #if (DEBUG)
and System.Diagnostics.Debugger.IsAttached
in visual studio? Are there cases of the DEBUG
It has nothing in common. You can debug the Release build. And you can run the Debug build without a debugger, press Ctrl+F5.
#if DEBUG
ensures the code is not included in the assembly at all in release builds. Also, code included by #if DEBUG
runs all the time in a debug build - not just when running under a debugger.
Debugger.IsAttached
means the code is included for both debug and release builds. And a debugger can be attached to release builds too.
It's common to use both together. #if DEBUG
is usually used for things like logging, or to reduce exception handling in internal test builds. Debugger.IsAttached
tends to just be used to decide whether to swallow exceptions or show them to a programmer - more of a programmer aid than anything else.
#if (DEBUG)
is a preprocessor directive that allows you to conditionally compile code.
System.Diagnostics.Debugger.IsAttached
provides a runtime value that indicates whether a debugger is attached to the process.
Conditional attributes are another related option to the ones listed above. Good answers related to this topic on this question.
Need .NET code to execute only when in debug configuration
private void ConfigureOAuthTokenConsumption(IAppBuilder app)
{
#if DEBUG
AuthenticateViaAppOwnIdentity(app);
#else
AuthenticateViaAzureAD(app);
#endif
}
With this code, just try to change the build from debug to release and vice-versa. The running/excluded code will show changed in VS automatically as black and grayed out respectively
#if DEBUG
is a compile-time check, meaning the code it surrounds will only be included in the output assembly if the DEBUG
preprocessor symbol is defined. Debugger.IsAttached
is a runtime check, so the debugging code still gets included in the assembly, but only executes if a debugger is attached to the process.