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

Recommended Answers

All 5 Replies

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

#if DEBUG
				Do this in debug;
#else
				do this optionaly if not in debug
#endif

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>?

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

Hi,

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

Thanks,
Kedar

Member Avatar for nathon

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
nathondalton.wordpress.com

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.