Curly Braces in string.Format in C#

By FoxLearn 11/10/2024 3:07:46 AM   77
In C#, if you want to use curly braces ({ and }) as literal characters within a string.Format() method, you need to escape them by doubling the braces.

If you got an error "Input string was not in a correct format." when using string formatting like this:

// Wrong
var str = string.Format("{ \"data\": {0} }", data); //System.FormatException: Input string was not in a correct format.   

The error "Input string was not in a correct format" typically occurs when there's an issue with how placeholders or format specifiers are used in a string.Format method.

// Correct
var str = string.Format("{{ \"data\": {0} }}", data);  

How to use Curly Braces in string.Format

string str = string.Format("This is a string with curly braces: {{ and }}");
Console.WriteLine(str); //This is a string with curly braces: { and }

To insert a single { or }, you use {{ and }}. The string.Format() method will interpret these as literal braces, not placeholders for variables.

If you want to combine placeholders and literal curly braces, you can do something like this:

int age = 38;
string result = string.Format("Your age is: {{ {0} }}", age);
Console.WriteLine(result); //Your age is: { 38 }

{0} is a placeholder for the age variable.

{{ and }} are used to include the literal curly braces around the number.

This method allows you to use curly braces both as part of the formatting system and as literal characters in the string.