1048

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
  • 153,850
  • 22
  • 249
  • 325
PhilB
  • 11,732
  • 2
  • 19
  • 15

1 Answers1

1590

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
  • 32,523
  • 5
  • 46
  • 71
  • 34
    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
  • 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
  • 5
    works with string literal in new c# as well `$"this will {{{something}}} to look like JSON"` – workabyte Dec 30 '16 at 01:28
  • This answer is only good if the string is a string literal you write. What if it is a string variable from another source? How can I escape the {} in a string variable like "hello {world}" to pass in to another method that wrongly tries to use it as a formatter? Do I use regular expression to replace {}? – Damn Vegetables May 24 '23 at 21:19