+1 vote
in C Sharp by

Difference between String and StringBuilder in C#?

1 Answer

0 votes
by

String

•      Belongs to the System namespace.

•      Immutable i.e. whenever you append a String object it creates a new object with new memory allocation.

•      When changed, a new object is created and old object is destroyed.

•      Avoid using inside loops, as if the loop executes N times. N memory allocation operations will be performed.

•      Concat function is used for String concatenation.

Example:

string s = "Jack";

s = string.Concat(s, "Mike");

StringBuilder

•      Belongs to the System.Text namespace.

•      Mutable i.e. whenever you append a String object it does not creates a new object with new memory allocation.

•      When changed, no new object is created or old object is destroyed.

•      Recommended for loops, as only the size of object will change.

•      Append function is used for String concatenation.

Example:

StringBuilder sb = new StringBuilder();

sb.Append("Jack");

sb.Append("Mike");

...