2

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.

jAC
  • 5,195
  • 6
  • 40
  • 55
sofsntp
  • 1,964
  • 23
  • 34
  • 1
    Visual studio runs the exe in the debug folder too, it just attaches a debugger. The conditional code is compiled in. – Crowcoder Sep 30 '16 at 12:50
  • See this for a couple of solutions : http://stackoverflow.com/questions/101806/check-if-application-was-started-from-within-visual-studio – PaulF Sep 30 '16 at 12:51

2 Answers2

11

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

Instead use Debugger.IsAttached to branch at runtime.

Dai
  • 141,631
  • 28
  • 261
  • 374
0

Just to make it clear, the statements beginning with a hashtag are pre-processor directives. These directives are not present in the Translation Unit; thus these conditional statements do not exist in the compiled file.

EDIT It seems that this whole translation unit thing doesn't apply for C#

Oran Can Ören
  • 97
  • 1
  • 2
  • 8
  • I'll be a pedant: it's "hash symbol"', "pound symbol", or "number sign" and not "hashtag". And the concept of Translation Units does not apply to the C# compiler. – Dai Sep 30 '16 at 13:04
  • @Dai Well, I was being a bit informal about the "hash symbol"; but I was unaware of the condition of translation unit for C#. Thanks for your input. – Oran Can Ören Sep 30 '16 at 18:48
  • @Dai To be a pedant as well, the official name is actually "octothorpe". :P – andidegn Aug 25 '22 at 10:53