简体   繁体   中英

How do you put an "IF DEBUG" condition in a c# program?

How do you put an "IF DEBUG" condition in a c# program so that, at run time, it will ignore a set of code if you are running in Debug mode and yet, execute a block of code if the program is not running in debug mode? A situation where this can be used is if a time stamp is taken at the start of a block and another time stamp is taken at the end. THey will hardly differ at run time. Yet, if you are stepping through the code in debug mode, they will differ a lot, and error conditions in an "if block" might be kicked off leading to the untimely (pun) execution of some code.

You just put your code in a block like this:

#IF DEBUG

//code goes here

#endif

This is not a runtime thing, this is a preprocessor directive, which means the code in that block won't even be compiled and will not be included.

If you want to check at runtime if you're debugging, you can check Debugger.IsAttached

Use the preprocessor instruction #if:

#if debug
    // run in debug mode
#else
    // run if not in debug mode
#endif

You can also use the

[Conditional("Debug")]

attribute on methods.

A couple more details:

  • You can wrap an entire method or just a code block or just a line of code.
  • You need to add using System.Diagnostics;
#if DEBUG
        // something
#elif
        // some other thing
#endif
#if (DEBUG)
...
#else
...
#endif

see here: http://bloggingabout.net/blogs/rick/archive/2005/03/10/2396.aspx

Since every other answer (but one) does not address your question, let me try:

If you wish to have a runtime switch, you'll need a way to get the information from your environment or the command line. Additionally, once you get that info, you'll need to apply it to your program.

1) For this you'll need a global variable.

bool bDebug;

2) get debugging information

bDebug = strcmp (getEnv ("DebuggingMode"), "1");  // you'll need to mess with this a little - do 'man getenv' and 'man strcmp' for an understanding of what I'm doing
  • or -

utilize the getopt() function to find out if debugging is turned off or on

3) every place in your code you want debugging turned on, check if bDebug is set

   if (bDebug) {
   // do something
   }
 if (System.Diagnostics.Debugger.IsAttached)
        {
            button3.Visible = true;
        }
        else
        {
            button3.Visible = false;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM