String vs StringBuilder in C#

By Santhosh N

This explains the difference between System.String and System.Text.StringBuilder

When we wanted to work with text in C#, normally we use String DataType to store the values.

Ex:
String str;
str = “EggHeadCafe”;

But, when we wanted to manipulate the value assigned to the str variable in later stages, we simple do something like this:

str = str + “ is the best .Net forum”;

everythings looks fine, and no issues.

But, one should understand what really happens doing so. Once any string value is manipulated, it creates a new  object in the memory and does not re-use the same memory space allocated initially as String types in .Net are immutable.

The alternative to address this is using of StringBuilder which is mutable type in .Net

Ex:
StringBuilder str = new StringBuilder();
            str.Append("EggHeadCafe");
            str.Append(" is best .Net forum");

             MessageBox.Show(str.ToString());

Conclusion: Always use SrtringBuilder when you have to change the values of the string types instead of string as this is the efficient coding standard.

Related FAQs

This explains about different type of arguments that can be passed to C# .Net methods.
This is how you can check if the given string is in numeric format or not in c#
String vs StringBuilder in C#  (1506 Views)