In this lesson, you will learn about the C# StringBuilder Class, its usage, important methods, and examples to better understand the topic.
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:
StringBuilder is useful when string manipulation is required, such as creating a log message or SQL Query.
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.
Below are the StringBuilder methods that each developer must know:
This method appends a string value to the StringBuilder variable. Example:
This method inserts a string at a specific index on the current StringBuilder value. Example:
This method removes a specific number of characters from a StringBuilder variable.
This method replaces a specific character from a StringBuilder variable. For Example:
You must often convert the StringBuilder final value to a string type. To do so, use the
.ToString() methods. For example:
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#