Question - What is the difference between String and StringBuilder in C#?
Answer -
The major difference between String and StringBuilder is that String objects are immutable while StringBuilder creates a mutable string of characters. StringBuilder will make the changes to the existing object rather than creating a new object.
StringBuilder simplifies the entire process of making changes to the existing string object. Since the String class is immutable, it is costlier to create a new object every time we need to make a change. So, the StringBuilder class comes into picture which can be evoked using the System.Text namespace.
In case, a string object will not change throughout the entire program, then use String class or else StringBuilder.
For ex:
string s = string.Empty;
for (i = 0; i < 1000; i++)
{
s += i.ToString() + " ";
}
Here, you’ll need to create 2001 objects out of which 2000 will be of no use.
The same can be applied using StringBuilder:
StringBuilder sb = new StringBuilder();
for (i = 0; i < 1000; i++)
{
sb.Append(i); sb.Append(' ');
}