Search code examples
c#compilationcil

Why does the compiler automatically generate a Debugger attribute for anonymous type?


When compiling a simple anonymous type code like this:

public class Test
{   
    public static void Main()
    {
        var my_anonymous = new { Name = "anonymous"};
    }
}

The IL code has a Debugger attribute for every generated method of the anonymous type. e.g. for Equals:

.method public hidebysig virtual instance bool 
          Equals(object 'value') cil managed
  {
    .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 )
  ... // rest of IL code

Why does the compiler generate it automatically? I compiled it with Microsoft (R) Visual C# Compiler version 4.6.1055.0, and (if this has any relevance) without using the VS cmd.

Note: There's this answer for removing the attribute (not possible), but I wonder about the "Why?".


Solution

  • This is the DebuggerHiddenAttribute - it simply tells the Visual Studio debugger that this is a generated type, don't stop inside its code. (Because the code was not written by the user - it was generated by the compiler.)

    Other debuggers are allowed to follow the same behavior - if you read the documentation, there's no semantics attached to this attribute, so all debuggers (or virtual machines) are free to interpret it any way they want (or are free to ignore it).