How to Escape Curly Braces with DebuggerDisplayAttribute

There are a zillion posts out there that describe how to use DebuggerDisplayAttribute. They all say about the same thing: put property names and other expressions inside curly braces. Like this:

[DebuggerDisplay("Name = {Name}, Value = {Value}")]
public class AnyClass  
{
    // ...
}

Voilà! The debugger experience has just been enriched.

So curly braces are special. That's great, but what if you want to include an actual curly brace in the display? Some of the .NET Base Class Library's own types display in the debugger with curly braces – System.Type, for example. Unfortunately, most articles (including MSDN, as of this writing) don't explain how to accomplish this.

To display a curly brace, just escape it with a backslash:

[DebuggerDisplay(@"\{Name = {Name}, Value = {Value}\}")]
public class AnyClass  
{
    // ...
}

Notice that the template string now is a verbatim string literal (@"..."). That is because we do not want the compiler to interpret { and } as escape sequences. Neither are valid C# escape sequences, and your code won't build if you try to use them as such. Rather, { and } are interpreted by the debugger at runtime. Thus, the backslashes themselves need to be compiled into the assembly verbatim.

In summary:

  • Use \{ and \} to display curly braces when using DebuggerDisplayAttribute
  • Use @"..." string literals if you want to use \{ or \}.