Does C# have a conditional compiler directive for debug mode? I have code that I want to run only if I'm debugging.

12 Years
Discussion Span
Last Post by nathon

Does C# have a conditional compiler directive for debug mode? I have code that I want to run only if I'm debugging.

yeah c# uses directives

				Do this in debug;
				do this optionaly if not in debug

That just made me do more research, which is good. Where, for example, does "DEBUG" come from? There is a #define directive, where one can define such constants. However, if you do a "#define DEBUG" in your code, then "#if DEBUG" is always true. That negates the purpose of a conditional.

There is also a Configuration Manager. In there, you can define various Builds, such as "Release" and "Debug". You can define your constants, such as DEBUG, in the Configuration Manager. Then, if you're compiling for Release, DEBUG isn't defined, and your conditional code won't execute.

All well and good, but my goal was to have code that would run when I'm actively debugging, and not when I'm not (regardless of whether I'm running a "Release" or 'Debug" version).

The compiler directives are of no use for this!

What I ended up doing: in the Configuration Manager, add a ficticious "command line argument". This will only be present when debugging. When executing the program outside of Visual Studio, no command line argument will be present.

I wrap my conditional code inside a test for the presence of a particular command line argument, one that will only exist while debugging.

What a kludge.


would Debug.Assert() do what you are trying to do>?


You can add the conditional compilers in the property pages of the solution also.



The DEBUG and TRACE are conditional constants defined in the project properties. The methods that don't run when these constants have this functionality because the methods are defined with a ConditionalAttribute set to either DEBUG or TRACE (e.g. [ConditionalAttribute("DEBUG")]) above the method. If you do not want your methods to operate under these conditions as well, then place this directive above your methods also. DEBUG and TRACE constants are defined in the properties of your project.

Nathon Dalton

Edited by nathon: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.