1067

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; }
0

1 Answer 1

1616

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; }
Sign up to request clarification or add additional context in comments.

7 Comments

Straight from the documentation: <quote>To specify a single literal brace character in format, specify two leading or trailing brace characters; that is, "{{" or "}}".</quote> msdn.microsoft.com/en-us/library/b1csw23d.aspx
Oddly enough, Microsoft removed the {{ notation from MSDN since version 4.5.
@Olivier I still get a FormatException when targeting .NET 4.5 with {} in the string; {{}} works.
For those wondering, the documentation wasn't removed, just moved. It's now at: msdn.microsoft.com/en-us/library/txafckwd.aspx
works with string literal in new c# as well $"this will {{{something}}} to look like JSON"
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.