Jan 20, 2020 in C Sharp
Q:

Difference between String and StringBuilder in C#?

1 Answer

0 votes
Jan 20, 2020

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");

Related questions

0 votes
Oct 18, 2019 in C Sharp
  • stringbuilder
  • string-in-c#
0 votes
May 6, 2020 in C Sharp
0 votes
Feb 16, 2020 in C Sharp
...