Escape curly brace '{' in String.Format

PhilB picture PhilB · Sep 22, 2010 · Viewed 225k times · Source

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

Answer

Richard Cook picture Richard Cook · Sep 22, 2010

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