-1

I ran into an issue where someone had apparently disabled the DEBUG and TRACE constants on a C# .NET project I was working on, so my calls to Debug.WriteLine were having no effect. (No debug output was shown in the output.) After re-enabling them as described here, I started seeing my output.

Knowing how to fix it is helpful, but my question is why? As far as I understand, DEBUG is a compile time constant, and the Debug class is already compiled when I build my project. So how are my calls to Debug.WriteLine skipped; shouldn't they be compiled like all my other code?

I can think of a few possible ways this could happen:

  • MS implemented some special "feature" in the compiler to remove these calls without the constant
  • Visual Studio sets up the debugger such that it does or doesn't listen based on this project setting for debug output when it runs
  • Debug has some crazy code that examines the calling assembly for some kind of flag set at compile time

MS's documentation indicates that this is expected behavior, but I haven't been able to track down any documentation about how it actually works. It could also be something that never even occurred to me, of course.

So how does it work?

Community
  • 1
  • 1
jpmc26
  • 28,463
  • 14
  • 94
  • 146

2 Answers2

1

Debug.WriteLine(..) calls are removed by the compiler if the DEBUG constant is not set at the time you compile your code.

One way to simulate this in your code is by using #if DEBUG, for example:

#if DEBUG 
    // This portion of the code will only exist in code compiled with the DEBUG constant set.
#end if

Another way is to add the ConditionalAttribute [Conditional("DEBUG")] to the top of your methods, which is what the Debug class does for WriteLine(..).

The exact details can be found at the following link on MSDN in the ConditionalAttribute documentation: https://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute(v=vs.110).aspx

Sean
  • 626
  • 5
  • 12
  • I just wanted to let you know that I do appreciate your answer. I debated a little about whether to request you update yours or Matt to update his, but I ended up choosing his since it got right to the point and was posted a little bit sooner. But still, thank you very much. =) – jpmc26 Jun 07 '16 at 00:18
1

Have a look at the Conditional attribute... It causes the method call to be ignored at JIT-time if the specified symbol is not defined. Most System.Diagnostic.Debug methods are defined using this attribute and the value "DEBUG" (see reference source for example), hence the calls don't occur if the DEBUG symbol is not defined at JIT-time.

nitzmahone
  • 13,720
  • 2
  • 36
  • 39