How to Escape Curly Braces with DebuggerDisplayAttribute

April 21, 2012 — 2 Comments

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:

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:

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 \}.

2 responses to How to Escape Curly Braces with DebuggerDisplayAttribute

  1. Nice! I found this useful.

    Essentially, you are just double-escaping: the backslash escapes the curly brace, and the literal string escapes the backslash.

    @"\{Name = {Name}, Value = {Value}\}" (literal string)
    could also be written:
    "\\{Name = {Name}, Value = {Value}\\}" (double backslash)

  2. Right. It’s just double-escaping.

Leave a Reply


Text formatting is available via select HTML. <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">