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?
views:
97answers:
4You 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()
{
}
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
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
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.