C# StringBuilder Class

In this lesson, you will learn about the C# StringBuilder Class, its usage, important methods, and examples to better understand the topic.

StringBuilder Class in C#

As we learned from the previous lesson, Stings are immutable and cannot change value once created. The StringBuilder allows a collection of characters to change variables; this property is called mutable.

To use the StringBuilder class in your program, you need to add the namespace System.Text at the top of your class:

using System.Text;

StringBuilder is useful when string manipulation is required, such as creating a log message or SQL Query.

Create a StringBuilder variable

To create a string builder, simply create an instance of its class:

StringBuilder sb = new StringBuilder();

You can also create a string Builder with an initial value:

StringBuilder sb = new StringBuilder("Learn CSharp Programming Language");

After a string builder is created and initialized, you can make changes to its value without worrying about exhausting the memory but using Built-in methods, which we will discuss in the next section.

C# StringBuilder Methods

Below are the StringBuilder methods that each developer must know:

StringBuilder Append

This method appends a string value to the StringBuilder variable. Example:

Before printing a string builder to the console, you must convert it to a String by using the .ToString() Method.

StringBuilder Insert

This method inserts a string at a specific index on the current StringBuilder value. Example:

StringBuilder Remove

This method removes a specific number of characters from a StringBuilder variable.

StringBuilder Replace

This method replaces a specific character from a StringBuilder variable. For Example:

C# Convert StringBuilder to String

You must often convert the StringBuilder final value to a string type. To do so, use the .ToString() methods. For example:

StringBuilder Example in C#

Below is a complete C# example that covers the methods we learned in this lesson:

This concludes the C# StringBuilder Class lesson. In the next lesson, you will learn about Booleans in C#