2

I am writing a code generation tool that frequently will have lines like

StringBuilder sp = new Stringbuilder();
sp.AppendFormat("        public {0}TextColumn()\n", className);
sp.AppendLine("        {"
sp.AppendLine("            Column = new DataGridViewTextBoxColumn();");
sp.AppendFormat("            Column.DataPropertyName = \"{0}\";\n", columnName);

However the issue I am having is when I run in to a line like this.

sp.AppendFormat("return String.Format(\"{0} = '{0}'\", cmbList.SelectedValue);", columnName);

I want the first {0} to turn in to whatever the value of columnName is but I want the seccond {0} to be left alone so the internal String.Format will process it correctly.

How do I do this?

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431

5 Answers5

13

Use double curly braces:

string result = string.Format("{{Ignored}} {{123}} {0}", 543);
Noldorin
  • 144,213
  • 56
  • 264
  • 302
Florian Reischl
  • 3,788
  • 1
  • 24
  • 19
7

Curly braces can be escaped by using two curly brace characters. The documentation of string.Format states:

To specify a single literal brace character in format, specify two leading or trailing brace characters; that is, "{{" or "}}".

In your example that would be

sp.AppendFormat("return String.Format(\"{0} = '{{0}}'\",cmbList.SelectedValue);", 
    columnName);
Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
3
sp.AppendFormat("return String.Format(\"{0} = '{{0}}'\", cmbList.SelectedValue);", columnName);
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
3

Use "{{0}}". This will result in the string "{0}"

1
String.Format(\"{0} = '{{0}}'\",
James Curran
  • 101,701
  • 37
  • 181
  • 258