If you’ve been around VB a while you know that concatenating strings, particularly large strings over about 1K, can be a time consuming task for your applications. To deal with this, Microsoft introduced the StringBuilder class in the .NET Framework in the System.Text Namespace. In this article we’ll look at the advantages of using it and go over some of the fundamentals of using it.

Why Use StringBuilder?

You still see a lot of code around that uses the old string concatination methods. That’s not surprising because it’s comfortable and familiar to use for most VB’ers. But, there are two good reasons to use StringBuilder for large or looped string concatenation operations: speed and readability.

Speed is really a no-brainer. Using StringBuilder averages around 10 times faster than the concatenation operator ‘&’ or the String.ConCat function. It’s highly optimized for fast string operations. Even C++ .NET programmers have trouble outperforming it.

Readability is the other advantage. How often have you seen, or even written, code like this:

This code is usually difficult to read and even more difficult to debug, especially if it goes on for 20, 30 or even 50+ lines like I’ve seen some code. It can even be difficult to code this originally since it’s quite easy to mistype something.

Append, AppendLine, and AppendFormat

We’ll begin looking at StringBuilder by taking a look at how we could build the same SQL statement above using StringBuilder and then taking a look at the Append commands. (Note that I don’t recommend building SQL statements dynamically like this due to SQL injection risks but it’s a good common string building example.)

That’s a lot cleaner and easier to read, isn’t it? Now let’s look at the Append commands.

The Append function adds the specified value to the end of the builder. One neat thing about Append is that it not only takes a string argument but it has 19 overloads that allow you to append the major data types (Int, Long, etc.), a substring of a specified string, or the default .ToString value of an object. This makes it very powerful and easy to use as compared to standard concatenations that require type conversion (if you’re running Option Strict like you should be doing). Since it does the type conversions for you internally, this helps even more with the speed.

AppendFormat also adds the specified value to the end but also applies a format to it. In the example above, we’re using a custom format string for each line of the SQL statement that allows us to insert the value into the single quoted location without additional concatenation overhead. This method also accepts objects and does the conversion internally as part of the formatting logic.

The AppendLine adds the ‘default line terminator’, aka the CR/LF pair on all Windows systems, to the end of the builder. Optionally, you may also include a string as seen here:

With EmailBuilder
.AppendLine()
.AppendLine("Sincerely,")
.AppendLine()
.AppendLine(txtSignatureName.text)
End With

Oh, just in case you didn’t know, the standard .ToString method allows you to retrieve the internal string from StringBuilder. Also note that I like to use With blocks for it since it makes it easier to read, for me anyway.

Insert

Insert is a lot like Append in that it has overloads for most data types. However, with it, you can specify where in the character sequence the string (or string representation of an object) goes. A limitation of Insert is that unless you get the string that’s being built using the .ToString method and use the IndexOf method on the result you can’t get the position where you want to insert. This limits its usefulness a bit but it can be quick if you need to insert a hunk of text in the middle of a large string as seen in this example:

' Email built using a template
If txtPersonalMessage.Text.Length > 0 Then
EmailBuilder.Insert(EmailBuilder.ToString.LastIndexOf("Sincerely,") - 1, txtPersonalMessage.Text)
End If

Replace

Replace, as the name implies, allows you to replace a given string with another string. This is especially powerful for templating applications when you can replace a key value in the template with a value from a database query or a business object as shown in this example:

With EmailBuilder
.Replace("{customer_fullname}", CurrentCustomer.FullName)
.Replace("{customer_firstname}", CurrentCustomer.FirstName)
.Replace("{customer_city}", CurrentCustomer.City)
'more replacements after this
End With

Remove

Remove, as you might expect, allows you to remove a specified number of characters starting at a particular position. Once again, finding the position is a little tricky. It can be useful if you need to remove a paragraph from a template, as in this example:

'we're assuming we already have the position info we need
EmailBuilder.Remove(HolidayGreetingIndex, HolidayGreeting.Length)

That wraps up the basics of using the StringBuilder class. I hope you’ve found this article helpful in learning about this class and how to use it. Let me know if you liked this article or have comments/question by leaving a comment, using the contact me button, or using the rating stars.

Share This Article:These icons link to social bookmarking sites where readers can share and discover new web pages.