C# - Difference between String and Stringbuilder in C#, Asp.net

String

String is immutable. Immutable means once we create string object we cannot modify. Any operation like insert, replace or append happened to change string simply it will discard the old value and it will create new instance in memory to hold the new value.

Example

string str = "hi";
// create a new string instance instead of changing the old one
str += "test";
str += "help";
String Builder

String builder is mutable it means once we create string builder object we can perform any operation like insert, replace or append without creating new instance for every time.

Example

StringBuilder sb = new StringBuilder("");
sb.Append("hi");
sb.Append("test ");
string str = sb.ToString();

Differences
String

  • It’s an immutable
  • Performance wise string is slow because every time it will create new instance
  • In string we don’t have append keyword
  • String belongs to System namespace
StringBuilder

  • It’s mutable
  • Performance wise stringbuilder is high because it will use same instance of object to perform any action
  • In StringBuilder we can use append keyword
  • Stringbuilder belongs to System.Text namespace

Comments

Popular posts from this blog

SQL Query :- Create Tables,Primary key,Foreign key,Merge Statment

AngularJS

Check folder and Delete All Files from Existing Folder in C#