C# StringBuilder Class

Have you ever had an extremely long string you needed to use in an ASP.NET web page? Or after it is displayed, have you ever wanted to view the source of the page to see what the string is outputting? Well, if you want to do this with a standard string, then you either get one long line string or you have to add line breaks where you want them. Personally, I don’t like adding the line breaks, as it is one more place I can have something break. Thankfully Microsoft has addressed this with the StringBuilder class, which I graciously use every time I have long strings to deal with.
I want to build a string that will contain several SQL statements and I want to use StringBuilder to do so. Rather than showing also how to execute the statements, I am just going to print them to the screen. The example is very basic and would not really require the StringBuilder class, but it makes it very easy to follow. I have used this in the past when using data-controls that were Java Applets and I needed to write out all the param tags. Whenever I had one that wasn’t functioning properly, it was very difficult to just look at one long string. And very aggravating adding a ‘\n’ after every tag.

In order to use the StringBuilder class, you will need to reference System.Text.

<%@ Import Namespace="System.Text" %>

Next I want to create a method that will build the string.


<script runat="server">
public string sqlStatements()
{
}
</script>

Finally, let’s build the string.

<%@ Import Namespace="System.Text" %>
<script runat="server">
protected void Page_Load(object sender, System.EventArgs e)
{
    // call sqlStatements when the page is loaded.
    this.sqlStatements();
}

public void sqlStatements()
{
    StringBuilder sql = new StringBuilder();
    // The first line we use AppendLine because it sends appends newline at the end.
    // We can use Append on the second line since we are not looking to create a new line afterward. AppendLine would work though.
    sb.AppendLine("UPDATE mytable SET disabled=true WHERE thekey=2;");
    sb.Append("UPDATE mytable SET disabled=false WHERE thekey=3;");

    // Write to the screen. Will appear in a single line, but if you view source, it prints on 2 lines.
    // Makes it easy to troubleshoot when you have a long string.
    Response.Write(sb.ToString());
}
</script>

StringBuilder Class References:
StringBuilder Members

No comments yet

Leave a reply