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

kiss my armpit
  • 3,413
  • 1
  • 27
  • 50
  • possible duplicate of [string.format format string containing {](http://stackoverflow.com/questions/8402488/string-format-format-string-containing) – H H Mar 02 '14 at 20:28

3 Answers3

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 {

Matthew Cox
  • 13,566
  • 9
  • 54
  • 72
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...

jaket
  • 9,140
  • 2
  • 25
  • 44
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.

Mert Akcakaya
  • 3,109
  • 2
  • 31
  • 42