2

I have already seen from other answers that to escape the { or } char in C# string.Format() you use {{ or }}.

But what I need to do is format a string that looks like this:

{{tag}} 

However, when I try to escape the double curly braces like this:

string.Format("{{{0}}}", "tag"); 

or this:

string.Format("{{{{{0}}}}}", "tag"); 

The output is always this:

{tag} 

A different way I have found that works is:

StringBuilder output = new StringBuilder(); output.Append("{{"); output.Append("tag"); output.Append("}}"); 

But it seems silly to have to have all that just to format a string.

Am I missing something obvious?

2
  • 3
    Your second variant using 5 braces on each side works for me! string.Format("{{{{{0}}}}}", "tag"); ==> {{tag}} Commented Mar 20, 2014 at 22:38
  • 1
    Your second sample string.Format("{{{{{0}}}}}", "tag"); works perfectly. Commented Mar 20, 2014 at 22:38

2 Answers 2

5

In order to do this you need 5 braces on either side of the expression

Console.WriteLine("{{{{{0}}}}}", "tag"); 

The break down is

  • 2 for the first {
  • 2 for the second {
  • 1 for the first { in {0}
Sign up to request clarification or add additional context in comments.

1 Comment

Seems I had it correct the first time, I'm not clear what my issue was. A rebuild of the solution seemed to help. Thanks everyone
2

You can use code this way.

string.Format("{0}{1}{2}", "{{","tag","}}"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.