Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add debug code? (should go to Debug, shouldn't go to Release)

Tags:

c#

.net

I need to log a lot of information in my software for debugging. However I need this option only during development, I would prefer to exclude all this code in Release.

Of course I can surround the place I want to debug with "if":

if (isDebugMode()) {
  Logger.log(blahblah);
}

But because my software is pretty time-critical, I want to avoid a lot of unnesseray "if" tests.

I.e. I think I need analog of c "#define #ifdef #ifndef". Are there any technics in c# or .net to solve my task easily?

like image 505
Oleg Vazhnev Avatar asked Nov 27 '22 22:11

Oleg Vazhnev


2 Answers

You can use [ConditionalAttribute("DEBUG")] in front of your Logger.log method so it will only get compiled in debug mode and completely removed in release mode.

This is how the Debug class methods are all marked.

The upside of this compared to using the #if approach is that code with the Conditional attribute doesn't even exist at runtime, and all references to it get removed, instead of staying there with an empty body (or however you'd compile it conditionally).

like image 102
Blindy Avatar answered Nov 30 '22 11:11

Blindy


Why don't you instead use the DEBUG symbol?

#if DEBUG
  // debug only code here
#endif

Here is an article describing all of the preprocessor directives available to you in C#, and you are also able to define your own preprocessor variables in your project's properties menu.

like image 33
Ed S. Avatar answered Nov 30 '22 11:11

Ed S.