faisantp faisantp - 2 months ago 9
C# Question

Execute code only while debugging with Visual Studio

Is it possible to run specific code only when I am debugging the program via the debugging tools of Visual Studio?

If I use

#if DEBUG
or
Conditional(“DEBUG”)
the code is still triggered when running the .exe in the /Debug directory.

Dai Dai
Answer

The #if DEBUG is for Conditional Compilation, it does not affect execution at runtime.

Instead use Debugger.IsAttached to branch at runtime.