Emilia Szymańska Emilia Szymańska - 2 months ago 28
C# Question

StringBuilder AppendFormat throws IndexOutOfRangeException

I have a template define in a string:

public static string EntityClassBegginingTemplate =
@"using System.Collections.Generic;

//generated by the RuleDesigner
public abstract class {0}Base : {1}
{";


And then I'm trying it to format a string:

builder.AppendFormat(Templates.EntityClassBegginingTemplate, entityName, baseClass);


That line throw an exception:


IndexOutOfRangeException: Array index is out of range.
System.String.FormatHelper (System.Text.StringBuilder result, IFormatProvider provider, System.String format, System.Object[] args) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/String.cs:1912)
System.Text.StringBuilder.AppendFormat (IFormatProvider provider, System.String format, System.Object[] args) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Text/StringBuilder.cs:534)
System.Text.StringBuilder.AppendFormat (System.String format, System.Object arg0, System.Object arg1) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Text/StringBuilder.cs:555)


What mistake did I make?

Answer

I would assume that the opening curly brace for the class template is being interpreted as a placeholder. You'll need to escape any curly braces that you want treated as literal characters.

public static string EntityClassBegginingTemplate =
    @"using System.Collections.Generic;

     //generated by the RuleDesigner
    public abstract class {0}Base : {1}
    {"; <-- this is where the issue likely originated

As Ed Plunkett notes, you escape braces by using the double-brace notation , {{, as covered in the MSDN:

Opening and closing braces are interpreted as starting and ending a format item. Consequently, you must use an escape sequence to display a literal opening brace or closing brace. Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}"). Braces in a format item are interpreted sequentially in the order they are encountered. Interpreting nested braces is not supported.