String Builders in C#

String Builders In C#

 

A string is immutable in .NET, means that when we want to change anything in the string, it causes a new string at runtime and destroys the old one. It happens invisibly.

Ex:

string S;

S=”mahak”;

S +=”Garg”;

Console.WriteLine(S);

 

The last string has a reference, the previous one will be disposed of during Garbage Collection. It increases the Garbage Collection. We can avoid these temporary strings with the help of String Builder Class.

String builder can span multiple statements. Its default constructor creates a buffer of 16 bytes long, which grows as per our requirement. It improves the Performance by avoiding the temporary strings.

Ex:

System.Text.StringBuilder s=new System.Text.StringBuilder(20);

s.Append(“mahak”);

s.Append(“garg”);

string x=s.ToString();

Console.WriteLine(x);

 

Ebook Download
View all
Learn
View all