How to add debug code? (must go to Debug, should not go to Release)

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

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

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

But because my software is pretty critical, I want to avoid a lot of failed if tests.

those. I think I need an analogue of C # #define #ifdef #ifndef. Is there any technique in C # or .net to easily solve my problem?

+4
source share
5 answers

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

This is how all methods of the Debug class are marked.

The surface of this compared to using the #if approach is that code with the Conditional attribute does not exist at all at run time, and all references to it are deleted, and do not stay there with an empty body (or however, you must compile it conditionally).

+13
source

Why don't you use the DEBUG symbol instead?

 #if DEBUG // debug only code here #endif 

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

+7
source

As already mentioned, you can use a combination of "preprocessor" directives:

 #if DEBUG ThisWholeSectionIsTreatedAsACommentIfDEBUGIsNotDefined(); #endif 

and conditional attribute:

 Debug.Assert(x); // Call will be removed entirely in non-debug build because it has conditional attr 

However, it is important to understand that one of them is part of the lexical analysis of the program, and the other is part of the semantic analysis. Easy to get confused. My article on differences can help:

http://ericlippert.com/2009/09/10/whats-the-difference-between-conditional-compilation-and-the-conditional-attribute/

+3
source

You can use this as a native alternative only to register debugging:

 Debug.Write("blah blah"); 

which will only be logged if it is a debug assembly.

+2
source

In this case, a conditional attribute may help.

Something like that:

 class DebugModeLogger { [Conditional("DEBUG")] public static void WriteLog(string message) { //Log it } } 

Extract from MSDN: The Conditional attribute allows you to define conditional methods. The Conditional attribute indicates the condition, checking the conditional compilation symbol. Calls to the conditional method are included or excluded depending on whether this character is defined at the dial-peer. If a character is defined, the call is turned on; otherwise, the call (including the evaluation of call parameters) is omitted.

+1
source

All Articles