How can I enter sentences and lines of code that will only be executed in debug mode?

I have one application in which I need to make code changes almost all the time (changing cryptographic procedures, etc.), so my idea is that every time I make changes, all debugging parameters and variables are activated. I don’t want to comment and uncomment the code all the time, so my question is about simple lines of code that will only run in debug mode. ¿How can I achieve this?

+3
source share
4 answers

You can use the conditional code section:

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

[Conditional("DEBUG")] .

:

[Conditional("DEBUG")]
private void YourFunction()
{
}
+9

.

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

, :

#if DEBUG
         Console.WriteLine("DEBUG is defined");
      #else
         Console.WriteLine("DEBUG is not defined");
      #endif
+4

. :

#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

:

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

DoDebugOnly() DEBUG.

. TRACE - , Visual Studio, , , :

#define FOO

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

#endif
+1

Depending on what you are trying to do, you might consider a logging structure such as log4net or Protocol Logging . They will allow you to leave debugging messages in your code, but will only output them if the external configuration file says.

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

0
source

Source: https://habr.com/ru/post/1717980/


All Articles