0

Why do I need double { but a single } in the following string?

static void Main()
{

    Console.Write("a={0}, b={1}, c={{", 1, 2);
    foreach (var i in Enumerable.Range(1, 5)) Console.Write("{0},",i);
    Console.WriteLine("\b}");
}

enter image description here

1

3 Answers 3

5

Because when you use the templating approach with string.Format() or Console.Write() with "{0}" in strings, the bracket is a special symbol. Therefore, if you want to use an ACTUAL bracket, you need to escape it by doing "{{" which will output a single {

1
  • Thank you, I understood. The key is "When using {<integer>} templating then { or } must be escaped". Mar 2, 2014 at 0:11
1

http://msdn.microsoft.com/en-us/library/txafckwd.aspx, scroll to the section titled Escaping Braces

In short, curly braces have special meaning to the string formatter and need to be escaped if you want a literal curly brace in your output string. Similar to escaping double quotes in a string, etc...

1
Console.Write("a={0}, b={1}, c={{", 1, 2);

This method you are using is not taking a String, it is using the String.Format() which requires your string to be formatted using curly bracers.

Console.Write("a=1, b=2, c={");

should work with simple strings without doubling curly braces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.