Escape curly brace '{' in String.Format [duplicate]
Asked Answered
C

1

1056

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; }
Cambridgeshire answered 22/9, 2010 at 21:44 Comment(0)
A
1602

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; }
Abednego answered 22/9, 2010 at 21:45 Comment(7)
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.aspxNephrolith
Oddly enough, Microsoft removed the {{ notation from MSDN since version 4.5.Roselani
@Roselani I still get a FormatException when targeting .NET 4.5 with {} in the string; {{}} works.Sorbian
For those wondering, the documentation wasn't removed, just moved. It's now at: msdn.microsoft.com/en-us/library/txafckwd.aspxUnadvised
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.Opuscule
works with string literal in new c# as well $"this will {{{something}}} to look like JSON"Rally
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 {}?Sweatbox

© 2022 - 2024 — McMap. All rights reserved.