11

It seems like it would be ideal (in terms of readability) to use say Debug.WriteLine to write to output rather than a ton of #if DEBUG statements.

When the program is compiled in release mode, does all the overhead with the Debug.WriteLine go away as if it did not exist, or is the function still called, but nothing done internally?

If so, is there any way to obtain this functionality on a custom class, i.e., a static call would only be compiled in if we are in Debug mode?

Gustavo Mori
  • 8,319
  • 3
  • 38
  • 52
user623879
  • 4,066
  • 9
  • 38
  • 53

1 Answers1

19

It is called ConditionalAttribute and it is already there: Debug.WriteLine() calls are removed entirely when you compile in Release mode.

It is declared like this:

[ConditionalAttribute("DEBUG")]
public static void WriteLine(string message)

So any calls to it are removed if the DEBUG symbol is not declared, e.g., in the default configuration of a release build. (You can change what pre-processor symbols are defined for different build configurations in the project properties.)

The same is true for (almost?) every method in Debug. In fact, it is the main difference between Debug and Trace - Trace's methods stay in release also.

Gustavo Mori
  • 8,319
  • 3
  • 38
  • 52
Ivan Danilov
  • 14,287
  • 6
  • 48
  • 66
  • 3
    Not an answer, but even if you didn't know about the conditional attribute and put the entire method in and #if debug, it would get optimized out. http://stackoverflow.com/questions/11783/in-net-will-empty-method-calls-be-optimized-out – Kevin Stricker Jul 31 '11 at 16:14
  • 2
    @mootinator: Well, it is not the same. With `Coditional` everything is thrown out at compilation time. With empty method JITter still have to analyze things in runtime thus lowering performance. Not much but anyway. This way on the contrary JITter would never see this method call at all. – Ivan Danilov Jul 31 '11 at 16:17
  • 1
    Keep in mind that if you do some crazy string concatenation before you pass it in to Debug.Write/WriteLine, your string concatenation will be included in your release build. If you put your concatenation logic inside the function, it will get stripped out. So you might do your string concat like so: Debug.WriteLine(DoHugeStringCalculation()); ..otherwise you can use #if DEBUG around it all. – Gordon Glas Aug 31 '12 at 14:33