Search code examples
c#comments

Do in-line comments in C# code affect the compiled dll?


Consider a C# file with very little content e.g.

...
public void DoSomething()
{
    Console.WriteLine("Does Something!");
}
...

And the same snippet with a comment in it:

...
public void DoSomething()
{
    // This line does something!
    Console.WriteLine("Does Something!");
}
...

When the compiler comes along to put this file in a dll it will strip down the superfluous and make it machine-readable. Does this mean that both dll's are entirely identical? The two files obviously have a different number of lines and would hash to different values but does the compiler care? Would a blank line have the same impact of changing the file, e.g.

...
public void DoSomething()
{

    Console.WriteLine("Does Something!");
}
...

Solution

  • Does this mean that both dll's are entirely identical?

    Maybe. There's a bit of subtlety here.

    • By default, the C# compiler is not deterministic. That is, even with the exact same input, you could get different DLLs due to IDs being generated. I know there was a push towards making deterministic mode the default for .NET Core SDK projects, but I'm not sure whether that's happened. From the command line, just running csc with Roslyn 2.8.0.62830, deterministic is not the default
    • Line numbers don't affect the IL usually, but they will affect any PDB files being generated, so that the debugger knows which line in the source code corresponds with what IL. Even without a change in line numbers, the PDB files contain a hash of the source code so that the debugger can check it's looking at the "right" code.
    • Line numbers can have an effect anyway due to caller information attributes, as shown by the code below:

      using System;
      using System.Runtime.CompilerServices;
      
      class Program
      {
          public static void Main()        
          {
              // Remove this comment and get a different result
              PrintLine();
          }
      
          static void PrintLine([CallerLineNumber] int line = 0)
          {
              Console.WriteLine(line);
          }
      }
      

    With the comment there, this prints 9. Without the comment, it prints 8. The IL is different, as the line number is embedded there as a constant.

    If you're concerned about comments affecting performance, you definitely shouldn't. But if you're really bothered about whether any change is possible just by making changes that wouldn't normally affect behavior - yes, there can be subtle changes.