xarzu
xarzu

Reputation: 9479

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.

Upvotes: 11

Views: 10551

Answers (8)

marcoqf73
marcoqf73

Reputation: 1344

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

Upvotes: 3

KevinDTimm
KevinDTimm

Reputation: 14376

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
   }

Upvotes: 1

DOK
DOK

Reputation: 32831

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;

Upvotes: 0

BFree
BFree

Reputation: 103742

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

Upvotes: 19

Tim Goodman
Tim Goodman

Reputation: 23976

#if (DEBUG)
...
#else
...
#endif

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

Upvotes: 0

Arne
Arne

Reputation: 750

You can also use the

[Conditional("Debug")]

attribute on methods.

Upvotes: 8

simendsjo
simendsjo

Reputation: 4749

#if DEBUG
        // something
#elif
        // some other thing
#endif

Upvotes: 0

Steven Evers
Steven Evers

Reputation: 17196

Use the preprocessor instruction #if:

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

Upvotes: 8

Related Questions