7

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");

2 Answers 2

12

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>";
Sign up to request clarification or add additional context in comments.

6 Comments

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?
Since he's using the @ symbol before the string, a backslash will be interpreted literally as a backslash so nothing would be escaped
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.).
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.
@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.
|
6

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.