views:

1618

answers:

2

I'm running string.Format on a readonly string that contains a bit of HTML + javascript but I get a System.FormatException instead.

This is my format string:

<script type="text/javascript">
    function {0}_showHideFieldWindow() {
        if ({0}.IsCustomizationWindowVisible()) {
            {0}.HideCustomizationWindow();
        } else {
            {0}.ShowCustomizationWindow();
        }
    }
</script>

All i'm doing is passing in the object name. Like this:

string.Format(javascript, "grid");
+6  A: 

Since you have curly braces in the string you need to escape them by doubling them up ({{ and }}) to prevent the formatter from thinking they are tokens.

Your string initialization should look something like this:

String javascript = @"<script type=""text/javascript"">
         function {0}_showHideFieldWindow() {{
      if ({0}.IsCustomizationWindowVisible()) {{
          {0}.HideCustomizationWindow();
      }} else {{
          {0}.ShowCustomizationWindow();
      }}
     }}
    </script>";
Andrew Hare
Just out of curiosity, isn't the standard escape character in C# a backslash (\)? That is, shouldn't the curly braces be escaped with "\{\}" instead of "{{}}"? I do understand that the double braces work, but is it best practice?
Tomas Lycken
Since he's using the @ symbol before the string, a backslash will be interpreted literally as a backslash so nothing would be escaped
John Rasch
John is correct - since it is a verbatim string there are a few escapes that you can do and all of them involve doubling up the character (i.e. { become {{, " becomes "", etc.).
Andrew Hare
A backslash is used to escape illegal C# characters. A brace is legal in a C# string, It's the string.Format method that expects the string in its own legal format.
James Couvares
@Tomas: the \ is the escape character for string literals -- ie. it's used to enter 'special' characters into a string literal. For a format string however, you double the character you want to escape. Why? Well, because that's what the API says. Why did the API designers do that? Probably because they also had to make it work for people using VB.Net. Which is easier -- explaining to a VB-er to put \{, or explaining to C# users to use {{? I'd guess the latter is far easier.
Jonathan
Thank you all for the explanations! =)
Tomas Lycken
John is not correct on this. A backslash will not escape a brace regardless if a verbatim string is used. A brace is a legal character in a C# string (unlike a tab or newline etc...) It's the API's restriction.
James Couvares
+3  A: 

String.Format needs the extra brackets to be escaped. You might be better off doing something like this, which might be more readable than escaping each bracket if you don't need all of String.Format's functionality:

mystring.Replace("{0}","grid");
Keltex
+1 that's how I solved it originally.
James Couvares
+1 This would be simpler and would also be a bit faster.
Andrew Hare