StringBuilder Class
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
Overview
- A StringBuilder maintains an internal buffer instead of allocating a new string every time.
- Initial buffer size is 16 bytes, but can be passed via the constructor.
- Use a StringBuilder when appending lots of strings.
Good practice
- Use StringBuilder when excessively working with strings.
- See String Concatenation vs Memory Allocation for detailed analysis of string operations.
- Try to estimate the initial size for a StringBuilder whenever possible, this will avoid unneeded buffer growths.
Examples
Concatenating
public string GetBuildString()
{
StringBuilder builder = new StringBuilder();
builder.Append("SELECT column1,");
builder.Append(" column2,");
builder.Append(" column3,");
builder.Append(" column4,");
builder.Append(" column5,");
builder.Append(" column6,");
builder.Append(" FROM table1 t1");
builder.Append(" JOIN table2 t2");
builder.Append(" ON t1.column1 = t2.column1");
return builder.ToString();
}
You May Also Like
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



