Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#if (DEBUG) VS System.Diagnostics.Debugger.IsAttached

What is different between using #if (DEBUG) and System.Diagnostics.Debugger.IsAttached in visual studio? Are there cases of the DEBUG flag being set, but no debugger attached, or cases when a debugger could be attached when the DEBUG flag is not set?

like image 890
Sarawut Positwinyu Avatar asked Aug 16 '11 03:08

Sarawut Positwinyu


2 Answers

#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.

like image 92
Paul Stovell Avatar answered Oct 08 '22 17:10

Paul Stovell


#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.

like image 28
David Brown Avatar answered Oct 08 '22 16:10

David Brown