C# StringBuilder
String is immutable.
Meaning is every time you use methods in System.String class, you create a new instance of String class in a memory.
Creating new instances in memory for appending the string is costly and it consumes memory.
The System.Text.StringBuilder is a class which can modify String without creating new instance of string in memory.
using System.Text;
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder("This is default constructor string ");
string firstName = " MyName ";
string lastName = " MyLastName ";
sb.Append(firstName);
sb.Append(lastName);
Response.Write( sb.ToString() );
}
OutPut:
This is default constructor string MyName MyLastName
Description:
Here sb is only one instance and we are not creating new instances for concatinating the two or many strings.
Also, you can clear the sb by calling Clear method of it
sb.Clear();
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5