Posts
16
Comments
100
Trackbacks
18
Curly braces and string.Format()

Recently I was trying to use StringBuilder.AppendFormat to build some javascript, and was hit with an exception when trying to do this:

sb.AppendFormat("function {0}(args) { return false; }", someVariable);

The problem is that you can't have { or } inside an input string for string.Format(). The solution is actually fairly straightforward:

sb.AppendFormat("function {0}(args) {{ return false; }}", someVariable);

Instead of using "\" as an escape character, you would use { or } (depending on what you want to escape).

posted on Monday, March 05, 2007 2:08 PM Print
Comments
Gravatar
# re: Curly braces and string.Format()
Luke
3/5/2007 5:06 PM
Excellent. I had this problem a few weeks ago but never followed it up, worked around it just concatenating (im bad i know). I'll be sure to revisit it.
Gravatar
# re: Curly braces and string.Format()
Luke
3/5/2007 5:22 PM
Excellent. I had this problem a few weeks ago but never followed it up, worked around it just concatenating (im bad i know). I'll be sure to revisit it.
Gravatar
# re: Curly braces and string.Format()
Waqas
10/27/2007 8:28 AM
just repeat the bracket...

sb.AppendFormat("function {0}(args) {{ return false; }}", someVariable);
Gravatar
# re: Curly braces and string.Format()
Jon
12/8/2007 7:20 AM
This comes up quick on google. Thanks for the tip, it saved me some time.
Gravatar
# re: Curly braces and string.Format()
Andrew Baird
7/14/2008 2:14 PM
Great post, surprising that I've never needed to do this before now. Great to have it so quickly and easily answered.
Gravatar
# re: Curly braces and string.Format()
David
3/26/2009 4:43 PM
This is is great! Really saved me some time!
Gravatar
# re: Curly braces and string.Format()
Holf
10/13/2009 6:18 AM
Very handy when building regex clauses...
Thanks!
Gravatar
# re: Curly braces and string.Format()
Ian
11/20/2009 1:48 AM
thank you very much I had the same problem also generating a javascript serverside

Post Comment

Title *
Name *
Email
Url
Comment *  
News