How to tell if your C# code is running in debug mode (debug compil

G

Guest

How can I tell if my C# code is running in debug mode?

I need to execute some extra code only when my project has been compiled in
debug mode. In release mode I don't want to execute this extra code.

I was looking for something simple I could test like:

#if DEBUG
do_extra_code
#endif

But, the DEBUG constant doesn't seem to be defined automatically within
Visual Studio just because you've built your project in debug mode.

In the end I had to manually add a "Conditional Compilation Constant" to:
DEBUG in the project's property pages. Then my #if DEBUG statement worked as
expected.

Is there a predefined constant that I can check instead of having to set
this up myself in the project's property pages?

Thanks.
 
B

Bruce Wood

To determine whether you are actually running under the debugger, you
can test

System.Diagnostics.Debugger.IsAttached

as for simply whether your program was compiled /debug or not... anyone?
 
M

Mattias Sjögren

But, the DEBUG constant doesn't seem to be defined automatically within
Visual Studio just because you've built your project in debug mode.

It should be. It sure is in the debug configuration for all my project
templates.


Mattias
 
M

Mattias Sjögren

as for simply whether your program was compiled /debug or not... anyone?

Something like

if (myAssembly.IsDefined(typeof(DebuggableAttribute), false)) ...


Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top