Difference Between String & StringBuilder Class
In this guide, we will discuss what is the difference between String and StringBuilder in C#. String and StringBuilder in C# dotnet both are nothing more than a class. String is immutable which means it is not liable to change whereas StringBuilder is mutable which means it is liable to change. The namespace for C# StringBuilder class is System.Text and the namespace for C# String class is System.
In case of C# String, whenever you create an object which is nothing more than a string value, there is a reference variable which points to that object in the memory and when you make changes to the string value, it creates a new object in the memory and the same reference variable now points to the newly created object which makes previously created object completely useless. The previously created object will stay in memory until the garbage collector runs.
The C# StringBuilder class does exactly opposite to String class. Instead of creating a new object in the memory on change of string value, it makes changes to the same object. Unlike String class, it does not create more useless objects in the memory. This use of StringBuilder class in C# is extremely helpful from performance point of view if there is heavy string manipulation is involved. C# StringBuilder example is given below along with String class example which will demonstrate actual difference between String and StringBuilder in C#.
static void Main(string args)
string s1 = "C# ";
s1 += "Tutorials for Beginners";
StringBuilder s2 = new StringBuilder();
s2.Append("Tutorials for Beginners");