Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 424
xarzu Avatar asked Jun 16 '10 19:06

xarzu


2 Answers

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

like image 138
BFree Avatar answered Sep 25 '22 10:09

BFree


Use the preprocessor instruction #if:

#if debug
    // run in debug mode
#else
    // run if not in debug mode
#endif
like image 22
Steven Evers Avatar answered Sep 25 '22 10:09

Steven Evers