13

Possible Duplicate:
How to escape brackets in a format string in .Net

How do I put { or } in verbatim string in C#?

using System;

class DoFile {

    static void Main(string[] args) {
        string templateString = @"
        \{{0}\}
        {1}
        {2}
        ";
        Console.WriteLine(templateString, "a", "b", "c");
    }
}

I get error when I use '{' or '}' in verbatim string, I guess it's because '{' or '}' is used for parameter marking such as {0}, {1}, {2}. \{ doesn't work.

Unhandled Exception: System.FormatException: Input string was not in a correct format.
  at System.String.ParseFormatSpecifier (System.String str, System.Int32& ptr, System.Int32& n, System.Int32& width, System.Boolean& left_align, System.String& format) [0x00000] in <filename unknown>:0 
  at System.String.FormatHelper (System.Text.StringBuilder result, IFormatProvider provider, System.String format, System.Object[] args) [0x00000] in <filename unknown>:0 
Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871
  • Can you include the line of code that fails? Looks like you're using a variant of .Format which does treat { specially. – n8wrl May 13 '11 at 19:38
  • 2
    This is a problem because of using `Format`, not because of using a verbatim string. – jakebasile May 13 '11 at 19:39

3 Answers3

16

You just have to escape with double curly brackets..

{{ or }} respectively..

Something like below

string.Format("This is a format string for {0} with {{literal brackets}} inside", "test");

This is a format string for test with {literal brackets} inside

Nikhil Girraj
  • 1,135
  • 1
  • 15
  • 33
Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132
8

You put two like such {{ or }}.

Jim Bolla
  • 8,265
  • 36
  • 54
0

There is nothing special about putting { and } in a string, they should not be escaped. Besides, the escape character \ has no effect in a @ delimited string.

To use literal { and } in the format for the String.Format method, you double them. So, your format string would be:

string templateString = @"
    {{{0}}}
    {1}
    {2}
    ";
Guffa
  • 687,336
  • 108
  • 737
  • 1,005