Here I will explain the difference between string and stringbuilder in
c#.
String
String is immutable object (i.e.
once created cannot be changed ) and It always create new object of
string type in memory. If we want to append or replace something in
string then it will discard the old value and will create new instance in
memory to hold the new value. String belongs to “System” namespace.
Example
string str = "Hello Visitor";
// create a
new string instance instead of changing the old one
str += "How
Are";
str += "You ??";
|
Stringbuilder
StringBuilder is mutable, means if create string builder
object then you can make modification in the data i.e. you can append and
replace the string without creating new instance for every time.it will
update string at one place in memory doesn’t create new space in memory. Stringbuilder
belongs to “System.Text” namespace.
Example:
StringBuilder
strbuilder = new StringBuilder("");
strbuilder.Append("Hello");
strbuilder.Append("Visitor ");
string
str = sb.ToString();
|
Please mention in the comments in case you have any doubts
related to the post:
Difference between string and stringbuilder.