1010

How do I display a literal curly brace character when using the String.Format method?

Example:

sb.AppendLine(String.Format("public {0} {1} { get; private set; }", 
prop.Type, prop.Name));

I would like the output to look like this:

public Int32 MyProperty { get; private set; }
Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306
PhilB
  • 11,343
  • 2
  • 18
  • 14

1 Answers1

1534

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }
Richard Cook
  • 31,413
  • 5
  • 44
  • 69
  • 32
    Straight from the documentation: To specify a single literal brace character in format, specify two leading or trailing brace characters; that is, "{{" or "}}". http://msdn.microsoft.com/en-us/library/b1csw23d.aspx – Ben Voigt Sep 22 '10 at 21:49
  • 9
    Oddly enough, Microsoft removed the {{ notation from MSDN since version 4.5. – Olivier Jun 11 '13 at 13:30
  • 1
    @Olivier I still get a `FormatException` when targeting .NET 4.5 with `{}` in the string; `{{}}` works. – Danny Beckett Sep 07 '13 at 07:00
  • 68
    When we would like to get something like **{name}** as an output , it needs 3 curly braces as **string.Format("{{{0}}}",name)** – Davut Gürbüz Aug 28 '14 at 08:48
  • 4
    For those wondering, the documentation wasn't removed, just moved. It's now at: http://msdn.microsoft.com/en-us/library/txafckwd.aspx – Jason Sep 12 '14 at 18:59
  • 1
    **Related:** When using `Console.WriteLine(string)`, the curly braces do not need escapes. However, when using `Console.WriteLine(string, params object[])`, escapes are required. I've not tested how this applies for `String.Format` for when no additional arguments are added. – Nicholas Miller Apr 07 '16 at 16:04
  • 2
    works with string literal in new c# as well `$"this will {{{something}}} to look like JSON"` – workabyte Dec 30 '16 at 01:28