Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does application execute Console.WriteLine("Test"); in compiled version?

Tags:

c#

.net

I use a lot of lines like that

Console.WriteLine("Test");

to debug application under VS 2010.

My question is: Have I do comment all those lines when I build an application?

Thanks!

like image 277
Friend Avatar asked Nov 30 '22 05:11

Friend


1 Answers

Yes. In fact, if your app was a console application, you'd really want those lines executed. Have a look at System.Diagnostics.Debug methods (e.g. Debug.WriteLine) which may be what you need. Their output is in Visual Studio's Output window, and they do nothing in Release code.

More generally, you can have code that's only compiled in a Debug build by doing:

#if DEBUG
// Debug-only code here.
#endif

You can also put this attribute before your method definition to write a method that's not called at all when you do a Release build:

    [System.Diagnostics.Conditional("DEBUG")]

All these methods have the advantage that they shouldn't affect the performance of production code.

To check I'm giving you accurate advice, I compiled the following in Release mode:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello world!");

#if DEBUG
        Console.WriteLine("Inside #if block.");
#endif

        WriteLine("With ConditionalAttribute.");

        Debug.WriteLine("Debug.WriteLine.");
    }

    [Conditional("DEBUG")]
    public static void WriteLine(string line)
    {
        Console.WriteLine(line);
    }
}

I then used the IL Dissasembler tool to see what will actually run:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       11 (0xb)
  .maxstack  8
  IL_0000:  ldstr      "Hello world!"
  IL_0005:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000a:  ret
} // end of method Program::Main

As you can see, only the Console.WriteLine method is called. The other three alternatives are, as we had hoped, 'compiled out' of the debug code.

The Debug version looks like this:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       46 (0x2e)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldstr      "Hello world!"
  IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000b:  nop
  IL_000c:  ldstr      "Inside #if block."
  IL_0011:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0016:  nop
  IL_0017:  ldstr      "With ConditionalAttribute."
  IL_001c:  call       void ConditionalCompileTest.Program::WriteLine(string)
  IL_0021:  nop
  IL_0022:  ldstr      "Debug.WriteLine."
  IL_0027:  call       void [System]System.Diagnostics.Debug::WriteLine(string)
  IL_002c:  nop
  IL_002d:  ret
} // end of method Program::Main
like image 103
Olly Avatar answered Dec 05 '22 15:12

Olly