tags:

views:

97

answers:

4

I have one application in wich I need to make code changes almost all time (changing crytographic procedures, etc...), so my idea is to have all my debug parameters and variables activated each time I'm making changes. I don't want to be commenting and uncommenting code all the time, so my question refers to simple lines of code that will execute only in debug mode. ¿How can I achieve that?

+9  A: 

You may use a conditional code section:

#if DEBUG
    //Your code goes here.
#endif

Or, you can use the [Conditional("DEBUG")] attribute to zero out a whole function in a release build.

As in:

[Conditional("DEBUG")]
private void YourFunction()
{
}
John Gietzen
Note that using these two techniques at the same time can lead to confusing situations. See my recent article on the subject here: http://blogs.msdn.com/ericlippert/archive/2009/09/10/what-s-the-difference-between-conditional-compilation-and-the-conditional-attribute.aspx
Eric Lippert
Yeah, but the compiler warnings should be sufficient to find the problem.
John Gietzen
+4  A: 

Here's a good reference.

http://www.csharphelp.com/archives/archive36.html

From the source, here's a good example:

#if DEBUG
         Console.WriteLine("DEBUG is defined");
      #else
         Console.WriteLine("DEBUG is not defined");
      #endif
Nissan Fan
+1  A: 

The two main solutions are preprocessor directives and the Conditional attribute. The relevant preprocessor directive works as follows:

#if DEBUG
// Lines here are only compiled if DEBUG is defined, like in a Debug build.

#else

// Lines here are only compiled if DEBUG is not defined, like in a Release build.

#endif

The Conditional attribute is applied to a method:

[Conditional("DEBUG")]
public void DoDebugOnly()
{
    // Whatever
}

Then all calls to DoDebugOnly() are only compiled when DEBUG is defined.

Both methods work for any other preprocessor identifiers as well. TRACE is another example that is integrated into Visual Studio, but any preprocessor identifier you define works:

#define FOO

#if FOO
// Lines here are only compiled if FOO is defined.

#endif
Joren
A: 

Depending on what you're trying to do, you may want to consider a logging framework such as log4net or the Logging Application Block. These will let you leave debug messages in your code but will only output them when an external configuration file says to.

If you want to add/remove code that actually performs logic, though, go with the other answers.

TrueWill