StringBuilder Class in C#


About the StringBuilder Class

Strings in C# are immutable, after you assign a string object with initial value its data cannot be changed. Whenever an operation like concatenation is performed on string object, a new object of the string is created and original object is left for garbage collection, this is inefficient if the logic involves lot of string manipulation operations.

.NET framework class libraries provides StringBuilder type in System.Text namespace, StringBuilder objects are mutable, changes can be made in place on StringBuilder objects. Use StringBuilder in the routines that perform extensive sting manipulations, this will result in significant performance enhancement.

Capacity of StringBuilder Object

When StringBuilder is initialized it comes with a default capacity of 16, you can also set the initial capacity using the constructor while initializing or by setting the Capacity property. If the object reaches it capacity a new object is created with double the Capacity and the characters are copied to the new object. StringBuilder provides multiple custom constructors to initialize according to the requirements.

// Creating a StringBuilder Object with Capacity 256
StringBuilder builder = new StringBuilder("String builder sample", 256);

Important StringBuilder Class Methods

Append Method

Append method is used to append characters, this method has overloads which can take different types as input.

// Creating a StringBuilder Object with Capacity 256
StringBuilder builder = new StringBuilder("String builder sample", 256);

// Append string "1234"
builder.Append("1234");

Replace Method

This method replaces a value with the new value. It has overloads taking different types of inputs values and also starting index to find the  replace characters.

// Replacing string "1234" with empty string.
builder.Replace("1234", "");

ToString Method

ToString method without any parameters returns the string object representation of the characters in the StringBuilder. It has overloads which can return sub string of the characters.

// Returns the string object.
string stringObject = builder.ToString();

Insert Method

Inserts the string representation of the input value at a specified index, has overloads to take different type of input values.

// Insert "abcd" starting at index 1
builder.Insert(1, "abcd");