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.

2
  • 1
    Visual studio runs the exe in the debug folder too, it just attaches a debugger. The conditional code is compiled in. Commented Sep 30, 2016 at 12:50
  • See this for a couple of solutions : stackoverflow.com/questions/101806/… Commented Sep 30, 2016 at 12:51

2 Answers 2

11

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

Instead use Debugger.IsAttached to branch at runtime.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - is this suitable for running Unit Tests too though?
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#

3 Comments

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 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.
@Dai To be a pedant as well, the official name is actually "octothorpe". :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.